user3019319
user3019319

Reputation: 336

package access class |(different between public and protected)

if i have a pacakage access class somthing like this:

package AA;

class A {    
  // ...    
}

which is only accessed by classes on package AA. What is the difference between declaring on this class a methods as a protected or public? Isn't it is the same because the class only accessed from its pacakge ?

Upvotes: 1

Views: 68

Answers (2)

Eran
Eran

Reputation: 394156

Package AA might have a public class B that extends A.

In that case, a class C from a different package may create an instance of B and call any public methods of A for that instance.

If, however, you define methods of A as protected, C would have to be a sub-class of B in order to call those methods.

package AA;
class A 
{
    public void foo() {}
    protected void bar() {}
}

package AA;
public class B extends A 
{

}

package BB;
public class C extends B
{
    public void func ()
    {
        super.bar (); // OK, since bar is protected and C extends B
                      // which extends A
    }
    public static void main (String[] args)
    {
        B b = new B();
        b.foo(); // OK, since foo is public
        b.bar(); // doesn't compile, since bar is protected
    }
}

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136162

It makes difference when using reflection, like Class.getMethods()

Upvotes: 0

Related Questions