我正在阅读一本 JAVA 书籍并遇到了 Dynamic Method Dispatch。但这对我来说有点困惑(也许是因为我是新手)。书上说它是基于一个原则:一个超类引用变量可以引用一个子类对象。
class X{
void display()
{
System.out.println("This is class X");
}
}
class Y extends X{
void display()
{
System.out.println("This is class Y");
}
void play()
{
System.out.println("PLAY!");
}
}
class k{
public static void main(String args[]){
X obj1 = new X();
Y obj2 = new Y();
X ref = new X();
ref = obj1;
ref.display();
//output is :This is class X
ref = obj2; //Using the principle stated above
ref.display();
//output is :This is class Y
ref.play(); //Compiler error:Play not found
//well it must be because ref is of X type and for X no methods of its subclass "Y"
//is visible
}
}
所以我想问一下,如果 play() 不可见,那么为什么 Y 的 display() 可见?