我已经看到有关保护和包私有修饰符之间差异的各种文章。有一件事我发现这两个职位矛盾
在这个接受的答案中说
The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.
在这个接受的答案中说
To satisfy protected level access two conditions must be met:
The classes must be in the same package.
There must be an inheritance relationship.
不是矛盾吗?从我对其他文章的理解,第一篇文章给出了正确的答案,在其他包中protected == package-private子类。
如果这个语句是正确的,那么为什么这个代码在第17行的子类Cat上失败,出现以下错误消息
The method testInstanceMethod() from the type Animal is not visible
我的超级和子类代码如下。
package inheritance;
public class Animal {
public static void testClassMethod() {
System.out.println("The class" + " method in Animal.");
}
protected void testInstanceMethod() {
System.out.println("The instance " + " method in Animal.");
}
}
package testpackage;
import inheritance.Animal;
public class Cat extends Animal{
public static void testClassMethod() {
System.out.println("The class method" + " in Cat.");
}
public void testInstanceMethod() {
System.out.println("The instance method" + " in Cat.");
}
public static void main(String[] args) {
Cat myCat = new Cat();
Animal myAnimal = myCat;
myAnimal.testClassMethod();
myAnimal.testInstanceMethod();
}
}
请澄清为什么上述代码失败。这将是非常有用的。谢谢