在具有相同属性的两个不同对象上使用equal()方法

时间:2020-02-20 16:02:17

标签: java

说我有两个类./my_server_block.conf:/opt/bitnami/nginx/conf/server_blocks/my_server_block.confA,它们之间没有任何关系,并且都具有相同的属性B

然后为private int _x设置以下方法:

A

public boolean equals (A other) { return ((other!=null) && ( _x == other._x)); }

B

现在,如果我应用以下内容

public boolean equals (Object other) {
    return ((other!=null) && (other instanceof B) && (_x = ((B)other._x));
}

我希望得到B z1 = new B(10); Object z2 = new A(10); System.out.print(z1.equals((A)z2); ,因为编译器根据插入的对象(而不是指针)的类型来决定要运行哪种方法。

我知道这个网站讲的不是理论,而是有人可以发表评论并告诉我为什么我true运行此代码吗?

1 个答案:

答案 0 :(得分:2)

System.out.print(z1.equals((A)z2);

这会打印false,因为在B#equals实现中,other instanceof B的值为false

public boolean equals (Object other) {
    return ((other!=null) && (other instanceof B) && (_x = ((B)other._x));
                             ^^^^^^^^^^^^^^^^^^^^
}
相关问题