简体   繁体   中英

How to invoke original method inside an overridden method

class Object{

    String x;
    int y;

    Object (String a, int b){
        this.x = a;
        this.y = b;

    @Override
    boolean equals(Object obj){

         return (this.x.equals(obj.x)) && this.y == obj.y);
    }
}

Here I am trying to write a method that overrides equals() in order to equate two values, a string and an integer, at the same time. In order to test for string equality, I use the original equals() method that I am overriding.

Can I do this without errors? Or can I not use the original equals() method inside of a method overriding it? Is there a better way of achieving this?

I am not quite able to find answers to this question online, but that may be a result of not knowing the technical wording for a situation like this.

Thank you

I think the problem is that you're not correctly overriding the Object.equals() method. If you're trying to check that both the String and the int are equal in order for your object to be equal, it sounds like you want a new object to represent whatever the String and int together represent:

class MyObj {
    private String str;
    private int num;
    ...
}

(with appropriate getter and setter methods)

Then you can override MyObj.equals() like so:

@Override
boolean equals(MyObj that){
    /* First check for null and all that stuff */
    ...
    return this.str.equals(that.getStr()) && this.num == that.getNum();
}

Call:

super.whatevername();

Or in this case:

super.equals(someObject);

This will call the superclass' method

By the way, the original method for equals is

public boolean equals(Object obj)

By the way, your whole return block can be replaced by:

return (this.x.equals(obj.x)) && this.y == obj.y);

The way you did it is inefficient and makes me cringe :/

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