说我有两个类./my_server_block.conf:/opt/bitnami/nginx/conf/server_blocks/my_server_block.conf
和A
,它们之间没有任何关系,并且都具有相同的属性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
运行此代码吗?
答案 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));
^^^^^^^^^^^^^^^^^^^^
}