java - 使用各种重写方法调用对象方法

标签 java polymorphism overriding

我遇到了这段代码:

public class AAA
{
       protected int _num;
       public AAA()
        {
            _num=2;
        }
       public boolean equals(Object other)
       {
           System.out.println("objectA");
           return true;
        }
}
public class BBB extends AAA
{
    String st;
   public BBB()
        {
           st="bbb";
        }
   public boolean equals(Object other)
        {
        System.out.println("objectB");
        return true;
        }
   public boolean AAA(AAA other)
        {
        System.out.println("AAA");
        return true;
        }
   public boolean BBB(BBB other)
        {
        System.out.println("BBB");
        return true;
        }
}
public class Driver15a
{
    public static void main(String args[])
        {   
            AAA ab=new BBB();
            BBB b1=new BBB();
            if(ab.equals(ab)) System.out.println(6);
}
}

我希望 ab 能够:

-使用 AAA 的 equals 方法。

-使用对象签名从 BBB 调用方法。

但是它调用带有 BBB 签名的方法,这对我来说很奇怪。

非常感谢您提供有关此代码实际运行方式的反馈,以了解方法调用。 谢谢!

最佳答案

方法public boolean AAA(AAA)public Boolean BBB(BBB)与此无关。如果我将其减少到显示正在发生的情况所需的最少量代码:

public class AAA
{
    public boolean equals(Object other)
    {
        System.out.println("objectA");
        return true;
    }
}

public class BBB extends AAA
{
    public boolean equals(Object other)
    {
        System.out.println("objectB");
        return true;
    }
}

public static void main(String args[])
{   
    AAA ab=new BBB();
    ab.equals(ab);
}

这是多态性的一个基本示例。 BBB.equals(Object) 会覆盖 AAA.equals(Object),因此当您调用 ab.equals(ab) 时,它会找到最重写版本,BBB.equals(Object)

关于java - 使用各种重写方法调用对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35516090/

相关文章:

C# 对象初始值设定项想要使用错误的 Add 方法

java - 我如何计算xy坐标?

android - 如果 bool 值为真,则覆盖主页和后退按钮

python 3 : How to write a __iter__ method for derived class so that it extends on the behaviour of the base class' __iter__ method

django - 覆盖 Django 模型中的深度复制

java - JPA 标准 API : LEFT JOIN for optional relationships

java - Spring boot JPA Hibernate 返回嵌套的 Json 对象 : Reddit style comment system

java - 使用 facebook graph api 共享链接后,Android 解析 facebook 登录不起作用。

java - 用于弥补 Java 中基于多态参数的运行时方法查找不足的模式?

java - 在 JLabel 中用 int 换行的问题