测试中的多态性javaq
我有一个关于多态性的问题测试中的多态性javaq,java,Java,我有一个关于多态性的问题 public class A { protected int _i; public A(int i) { _i = i; } } //----------------------------------------------------------// public class B extends A { public B(int i) { super(i+1); } } //------------------
public class A
{
protected int _i;
public A(int i)
{
_i = i;
}
}
//----------------------------------------------------------//
public class B extends A
{
public B(int i)
{
super(i+1);
}
}
//----------------------------------------------------------//
public class C extends B
{
public C(int i)
{
super(i);
}
public boolean equals (Object other)
{
return ((other!=null) &&
(other instanceof C) &&
(_i==((C) other)._i));
}
}
//----------------------------------------------------------//
public class D extends B
{
public D(int i)
{
super(i+1);
}
public boolean equals (D other)
{
return ((other!=null) &&
(_i==((D) other)._i));
}
}
public class tester {
public static void main (String [] args) {
A a = new A(1);
B b = new B(1);
C c = new C(1);
D d = new D(1);
B b1 = new D(1);
Object c1 = new C(1);
Object d1 = new D(1);
System.out.println (d1.equals(d));
}
}
为什么打印的结果是假的?
当我改变D中的equals方法来接收对象而不是D时,它的打印结果是真的,但是怎么办呢?
请帮忙谢谢你已经得到了一半的答案。“当我改变D中的equals方法以接收对象而不是D时,它打印的是True”实际上是这个问题的关键部分。您需要了解的是重写和重载之间的区别
public boolean equals (D other)
{
return ((other!=null) &&
(_i==((D) other)._i));
}
此方法将创建一个特定于D
类的equals(D)
版本,除了对象中先前存在的equals(Object o)
之外。这是因为它们有不同的方法签名,称为重载。但是,这一点非常有效:
public boolean equals (Object other)
{
return ((other!=null) &&
(_i==((D) other)._i));
}
这是因为它覆盖了超类版本的equals(objecto)
。最后一个音符。我知道您没有编写这段代码,但最好这样编写此方法:
public boolean equals (Object other)
{
if(other instanceof D)
return ((other!=null) && (_i==((D) other)._i));
return false;
}
这样,如果您试图将D
与不相关的对象或继承树中较低的对象进行比较,就可以避免出现ClassCastException