11

Possible Duplicate:
How to make data member accessible to class and subclass only

In java,
protected members can be accessed from within the class, its subclasses and from all the classes present in same package,
but i want a member to be accessible only from the class and its subclasses(as like protected member in c++).

for eg::

class A
{
    protected void fun()
    {
        System.out.println("Hello");
    }
}
class B
{
    public static void main(String args[])
    {
        A a = new A();
        a.fun();        
    }
}

here, A's fun() is accessible to B, even if B is not the subclass of A.

How can make A unaccessible to all the classes which are not the subclass of A?

edit:: i want to achieve this in java.

Community
  • 1
  • 1
Eight
  • 4,194
  • 5
  • 30
  • 51
  • this might be useful - http://stackoverflow.com/questions/1505010/java-class-whose-fields-are-only-accessible-to-its-subclasses-without-getters-s – FSP Jun 01 '12 at 14:49

3 Answers3

9

In Java, there is no way to do this.

That said, you (ideally) control all the code in your package, so you'll just have to make sure you don't use it yourself.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • Just curious, is there any mechanism to prevent others from simply declaring their code in your package? – matts Jun 01 '12 at 15:28
  • 1
    @matts See Polygnome's answer. You can seal your jar to prevent the declaration of new classes in your package. – Mesop Jun 01 '12 at 15:30
  • 2
    Reportedly, http://docs.oracle.com/javase/tutorial/deployment/jar/sealman.html works. But reflection allows any code to get around visibility restrictions like `private` or protected: there's really no way to stop code that wants to from getting your internal variables. So...basically, you can't stop it from happening, only make it more difficult, which `protected` does. – Louis Wasserman Jun 01 '12 at 15:31
  • @LouisWasserman Well, you can add a SecurityManager that prevents that access. But in almost all cases that would be overkill. – Jochen Jun 01 '12 at 16:14
3

There is no way to do that in java. Protected means that is is visble to inheritors and classes within the same package. But you can seal your package (http://docs.oracle.com/javase/tutorial/deployment/jar/sealman.html) so that no-one may create new Classes within your package.

Mesop
  • 5,187
  • 4
  • 25
  • 42
Polygnome
  • 7,639
  • 2
  • 37
  • 57
2

In Java, protected means "accessible by inheritors and others in the same package."

In C++ protected means "accessible by inheritor".

They are not really equivalent because of the package accessibility in Java.

The only way that you can mimic the C++ protection in Java is by declaring classes in their own package, but I don't recommend that.

Mesop
  • 5,187
  • 4
  • 25
  • 42