1

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 ?

2 Answers 2

1

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 } } 
Sign up to request clarification or add additional context in comments.

2 Comments

The different package restriction for C is important, from the same package, C could access the protected fields/methods too without extending either A or B. (protected includes package private access.)
@GáborBakos Yes, that's why C is in a different package in my example.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.