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() が表示されるのですか??