Search code examples
javac++protectedaccess-specifier

c++ like protected in java


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.


Solution

  • 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.