Re: access control
David Breton wrote:
Hi,
I would like to have this setup:
I have a class call it A that is part of some package, say P. Every
class in P can access the public methods of A. That's fine because I
need the other classes in P to be able to call those public methods.
Every class in P,Q,R,S,... can call the public methods of A.
The meaning of `public' is "Anybody at all can see me/call me."
class B is also part of package P. I want A and B to be the only
classes that can instantiate objects of class A. How do I achieve
this? Is this even possible?
If A and B are the *only* classes in P, then specify no
access at all for the constructors of A: don't say `public',
don't say `protected', don't say `private'. The default is an
access often called "package-private," meaning "visible only
to classes in the same package." So if A and B are the only
classes in P, then A and B will be (ipso facto) the only classes
that can call A's constructors.
I known one solution is to define another package Q and stick A and B
in Q and give A protected constructors. But I want to know if it's
possible without creating another package.
You misunderstand `protected'. It means "accessible from
any code in this class (like `private') plus any code in the
same package (like "package-private") plus any code in any class
anywhere that happens to extend A."
That is, `protected' is *less* "protected" than nothing.
--
Eric Sosman
esosman@ieee-dot-org.invalid