我读了两个程序,都将多态对象引用传递给方法。我很困惑运行时的方法是否取决于引用类型或实际对象。
程序1:
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);
}
}
方案2:
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中,方法根据引用类型运行。我无法理解它们之间的区别。
如果有详细的解释,我们将不胜感激。
最佳答案
在第二个程序中,它打印显示形状
,因为方法displayShape()
的基本实现未被重写。该方法未在 PlayerPiece
类中实现。因此它继承了其父类的行为,即 GameShape
。
按如下方式编辑第二个程序以获得所需的结果:
class PlayerPiece extends GameShape
{
public void movepiece()
{
System.out.println("moving game piece");
}
public void displayShape()
{
System.out.println("Displaying player piece");
}
}
然后你的程序将打印:显示玩家棋子
这种技术称为方法重写,您可以在子类中实现从父类继承的方法的功能。
关于java - 对象类型和引用类型之间真的很困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16712399/