private access modifiers in Java?
This question already has an answer here:
The first answer is basically correct - protected
members can be accessed by
However, there is a little trick:
6.6.2 Details on protected Access
A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.
It means that subclass from other package cannot access protected
members of arbitrary instances of their superclasses, they can only access them on instances of their own type (where type is a compile-time type of expression, since it's a compile-time check).
For example (assuming that this code is in Cat
):
Dog dog = new Dog();
Animal cat = new Cat();
dog.testInstanceMethod(); // Not allowed, because Cat should not be able to access protected members of Dog
cat.testInstanceMethod(); // Not allowed, because compiler doesn't know that runtime type of cat is Cat
((Cat) cat).testInstanceMethod(); // Allowed
It makes sense, because accessing of protected
members of Dog
by Cat
may break invariants of Dog
, whereas Cat
can access its own protected
members safely, because it knows how to ensure its own invariants.
Detailed rules:
6.6.2.1 Access to a protected Member
Let C be the class in which a protected member m is declared. Access is permitted only within the body of a subclass S of C. In addition, if Id denotes an instance field or instance method, then:
6.6.2.2 Qualified Access to a protected Constructor
Let C be the class in which a protected constructor is declared and let S be the innermost class in whose declaration the use of the protected constructor occurs. Then:
See also:
In protected access the members are accessed in the same package and for inherited class member in another package can also be accessed.
In package access the members of the classes in the same package can be accessed. Class members in other packages can't be accessed in package access.
You have created an Cat instance and cast it to its super class type ie Animal type. As per Animal type its testInstanceMethod is visible in same package or any subtypes. If you didn't cast to Animal type the code will compile.
Hope that helps
./Arun
链接地址: http://www.djcxy.com/p/4120.html上一篇: 何时在shell变量中引用引号?
下一篇: Java中的私人访问修饰符?