简体   繁体   中英

Call parent class function on derived class object (Java)

I have three classes:

Parent

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;
        }
    }
}

Child

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;
        }
    }
}

MiddleChild

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;
        }
    }
}

Basically, I want to compare a Child and a MiddleChild using only their common properties (ie, the properties defined in Parent ). For example, if I create a Parent object with a parentValue of 7 and a Child (or MiddleChild ) object with the same parentValue, as in the snippet below, parent.equals(child) evaluates to true. I would like to somehow call the equals function of the Parent object from the Child class. Is this even possible? I understand why the code below prints "failure"; is there an alternative method to access the Parent.equals function to compare child and middle ? Obviously, the super object is not useful as I'm trying to compare two objects from some function external to both Child and MiddleChild .

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");
    }
}

The output of this snippet is

Parent = Middle
failure

This idea seems to be a poor design to use equals() in this manner. You should really create a method in Parent called getParentValue(). Then you would compare using if( child.getParenvValue() == middle.getParentValue() )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM