简体   繁体   English

如何在重写方法中调用原始方法

[英]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. 在这里,我试图编写一个覆盖equals()的方法,以便同时将两个值(字符串和整数)等同起来。 In order to test for string equality, I use the original equals() method that I am overriding. 为了测试字符串相等性,我使用了我重写的原始equals()方法。

Can I do this without errors? 我可以毫无错误地这样做吗? Or can I not use the original equals() method inside of a method overriding it? 或者我可以不在覆盖它的方法中使用原始的equals()方法吗? 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. 我认为问题是你没有正确覆盖Object.equals()方法。 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: 如果您正在尝试检查String和int是否相等以使对象相等,则听起来您希望新对象表示String和int一起表示的内容:

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

(with appropriate getter and setter methods) (使用适当的getter和setter方法)

Then you can override MyObj.equals() like so: 然后你可以像这样覆盖MyObj.equals():

@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 顺便说一下,equals的原始方法是

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 :/ 你这样做的方式效率低下让我感到畏缩:/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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