Frage

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.

War es hilfreich?

Lösung

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.

Andere Tipps

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.

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top