我在两个不同的包中有以下两个类。我的实例方法的访问修饰符受到保护,这意味着相同或不同包中的任何子类都可以访问它吗?但是,在 Eclipse 中,我Cat
在第 17 行的子类中看到以下消息
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();
}
}