0

我有三个班级:

家长

public class Parent {

    protected int parentValue;

    public Parent(int parentValue){
        this.parentValue = parentValue;
    }

    public boolean equals(Object obj){
        if(obj instanceof Parent){
            return ((Parent) obj).parentValue == parentValue;
        }else{
            return false;
        }
    }
}

孩子

public class Child extends Parent{

    protected int childValue;

    public Child(int parentValue, int childValue){
        super(parentValue);
        this.childValue = childValue;
    }

    public boolean equals(Object obj){
        if(obj instanceof Child){
            Child child = (Child) obj;
            return child.childValue == childValue &&
                    child.parentValue == parentValue;
        }else{
            return false;
        }
    }
}

中子

public class MiddleChild extends Parent{

    public MiddleChild(int parentValue){
        super(parentValue);
    }

    public boolean equals(Object obj){
        if(obj instanceof MiddleChild){
            return ((MiddleChild) obj).parentValue == parentValue;
        }else{
            return false;
        }
    }
}

基本上,我想比较 aChild和 aMiddleChild只使用它们的共同属性(即,定义在 中的属性Parent)。例如,如果我创建一个具有7的Parent对象和一个具有相同 parentValue 的(或)对象,如下面的代码片段所示,计算结果为真。我想以某种方式从类中调用对象的函数。这甚至可能吗?我明白为什么下面的代码会打印“失败”;是否有其他方法可以访问函数来比较和?显然,该对象没有用,因为我试图比较两个对象外部的某个函数和.parentValueChildMiddleChildparent.equals(child)equalsParentChildParent.equalschildmiddlesuperChildMiddleChild

public static void main(String[] args){
    Parent parent = new Parent(7);
    Child child = new Child(7, 3);
    MiddleChild middle = new MiddleChild(7);

    if(parent.equals(middle)){
        System.out.println("Parent = Middle");
    }

    if(((Parent) child).equals(middle)){
        System.out.println("success!");
    }else{
        System.out.println("failure");
    }
}

这个片段的输出是

Parent = Middle
failure
4

1 回答 1

0

以这种方式使用 equals() 的想法似乎是一个糟糕的设计。你真的应该在 Parent 中创建一个名为 getParentValue() 的方法。然后你会比较使用if( child.getParenvValue() == middle.getParentValue() )

于 2019-12-04T19:31:03.950 回答