Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ like protected in java [duplicate]

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.

like image 966
Eight Avatar asked Jun 01 '12 14:06

Eight


2 Answers

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.

like image 169
StandByUkraine Avatar answered Oct 01 '22 14:10

StandByUkraine


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.

like image 34
Louis Wasserman Avatar answered Oct 01 '22 12:10

Louis Wasserman