【发布时间】:2013-07-14 06:14:39
【问题描述】:
我正在阅读一本 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
}
}
所以我想问如果 玩() 不可见那为什么 展示() 的 Y 是可见的??
【问题讨论】:
-
ref的类型为X。因此,您只能访问class X中定义的方法签名。
标签: java inheritance