|
Re: Controlling Access to Class Members
|
Posted: Jul 11, 2008 1:05 AM
|
|
> 1- can a constructor be private ?
Yes
> In what cases?
In a situation where you require one instance of the class throughout the lifetime of your application - as per Singleton Class.
e.g
public class A {
private static A myA;
private A() {
}
public static A getInstance() {
if (myA == null)
myA = new A();
return myA;
}
}
So everytime you want the singleInstance of A for this App. you go:
A myInstance = A.getInstance();
> > 2-Imagine a method of a super class#1 in package#1 is > private , can sub classes of super class#1 in package#2 > have access to that method?
No, unless you use Relflection - in which case you will probably be creating a framework of somesort.
> If not , then what about > Inheritance ?
What about it? the method is private, why should a subclass have access to it?
> If yes , then what about being private ?
Once again, what about it? If you are really eager to access/call private methods from any class - whether its a SubClass or a totally unrelated class, you can access/ call the method or even the private attributes via reflection.
A lot of Frameworks generally use reflection - to give the impression that things are just working magically.
Take a look at the BeanUtils class from Apache commons to figure out how private properties of classes are copied over.
Hope this answers your questions.
|
|