我读了两个程序,都将多态对象引用传递给方法。我很困惑运行时的方法是否取决于引用类型或实际对象。
方案一:
class A
{
public void display()
{
System.out.println("A's display method");
}
}
class B extends A
{
public void display()
{
System.out.println("In B's display method");
}
}
class Displayer
{
public void foo(A ob)
{
ob.display();
}
}
class Tester
{
public static void main(String ar[])
{
B ob=new B();
Displayer ob1=new Displayer();
ob1.foo(ob);
}
}
方案二:
class GameShape
{
public void displayShape()
{
System.out.println("displaying shape);
}
}
class PlayerPiece extends GameShape
{
public void movepiece()
{
System.out.println("moving game piece");
}
}
class TilePiece extends GameShape
{
public void getAdjacent()
{
System.out.println("getting adjacent tiles");
}
}
class TestShapes
{
public static void main(String ar[])
{
PlayerPiece player = new PlayerPiece()
TilePiece tile = new TilePiece()
doShapes(player);
doShapes(tile);
}
public static void doShapes(GameShape shape)
{
shape.displayShape();
}
}
在程序 1 中,该方法基于实际对象运行,而在程序 2 中,该方法基于引用类型运行。我无法理解它们之间的区别。
详细的解释将不胜感激。