Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何比较派生类对象和基类对象java?_Java - Fatal编程技术网

如何比较派生类对象和基类对象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
),您需要准确地定义
基本
对象和
派生
对象应在何时相等