java - 对象类型和引用类型之间真的很困惑

标签 java object types reference

我读了两个程序,都将多态对象引用传递给方法。我很困惑运行时的方法是否取决于引用类型或实际对象。

程序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/

相关文章:

Java编程帮助和android开发

c++ - Lua - 反射 - 获取对象上的函数/字段列表?

excel - 使用 Excel VBA 创建 Word 应用程序 : Run-time error '429' : ActiveX component can't create object

java - 创建对象后不能从静态上下文引用非静态变量

scala - 给定方法参数返回最具体的类型

c - mspgcc 中的意外结果

java - 如何在禁用 Swing D&D 时覆盖 JTextPane 的选择行为?

java - 我在 GridLayout 中遇到问题,我想在里面显示 49 个按钮,但它不起作用 Android Studio

java - 如何扫描 Maven 存储库?

c++ - SDL/C++ 包含问题