如何比较派生类对象和基类对象java?
如何比较派生类中的基类对象和派生类对象?我需要将如何比较派生类对象和基类对象java?,java,Java,如何比较派生类中的基类对象和派生类对象?我需要将true作为以下代码的输出: class Base { int i; String str; } class Derived extends Base{ double d; String str1; public static void main(String []a){ Base b= new Base(); Derived d = new Derived();
true
作为以下代码的输出:
class Base {
int i;
String str;
}
class Derived extends Base{
double d;
String str1;
public static void main(String []a){
Base b= new Base();
Derived d = new Derived();
System.out.println("Equals! :"+d.equals(b));
}
}
它总是将
false
作为输出。如何将基类与派生类进行比较?好吧,让它返回true非常简单:
@Override
public boolean equals(Object other) {
return true;
}
然而,我认为这不是您应该做的(即使是在稍微不那么琐碎的实现中)
我认为Object
中的equals
方法不应该返回true
,除非类型实际上相同。否则,就确保满足Object.equals(Object)
所要求的对称性而言,它最终会让生活变得非常棘手。在那一点上,它也感觉不到它在实现自然的平等
然而,编写一个能够比较Base
的任意两个实例的类在您的特定情况下是否相等是完全合理的。等式比较器的好处在于,它们不必那么自然——你没有定义等式对于整个类型应该意味着什么——你只是描述了一个特定的比较
不幸的是,Java没有与
比较器
配套的EqualityComparator
(或其他)接口。这使得创建(比如)使用特定相等思想(以及与之配套的哈希代码)的映射和集变得更加困难。在你的情况下,这可能是一个问题,也可能不是问题——你希望如何使用这种平等比较呢?如果它在您自己的代码中,您可以编写自己的EqualityComparator
接口。如果您要构建一个映射或集合,这就不那么容易了:(对象相等通常是为同一类的对象定义的,例如:如果两个对象的Base b1、b2
的str
和i
值相等,那么您可能需要定义相等()(通常还有hashCode()
)方法来测试此条件。例如:
public boolean equals(Object obj)
{
// test for identity
if (this == obj) return true;
// check that obj is not null, and that it is an instance of Base
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
// compare attributes
Base other = (Base) obj;
if (i != other.i) return false;
if (str == null && other.str != null) return false;
if (!str.equals(other.str)) return false;
return true;
}
在您的例子中,由于Base
和Derived
是不同的类,具有不同的属性(Base
具有str
和i
,而Derived
具有str
、i
、str1
和d
),您需要准确地定义基本
对象和派生
对象应在何时相等