How to avoid B Class object creation from outside world, and allow through only A Class ?
I have 2 classes
public class A {
B obj = null;
public A() {
obj = new B();
}
public void methodA () {
obj.methodB();
}
// other methods
}
public class B {
public void methodB () {
// some logic
}
//other methods
}
public class Client {
public static void main (String s[]) {
// Valid Call
A obj = new A();
obj.methodA(); // Since methodB is called internally
// Invalid Call , How to restrict this B object creation here ?
B objB = new B();
objB.methodB();
}
}
Here is solution, its working ..
A, B, Client class may be in any package.
using public static boolean isFromAClass = false; field, it is achieved.
Only I need to change, instead od generalized Exception, it should be customized Exception as OutSideAClassBClassInstanceShouldNotBeCreated