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 ?
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
}
}
使用反射时会有所不同,例如Class.getMethods()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.