简体   繁体   中英

java object comparison and inheritance

Need your help with a practice question

how can i modify the below Bar class so that o.equals(0) returns false, you're not allowed to override equals() inherited from the superclass?

 public class Scratchpad {
    public static void main(String[] args) {
        Bar o = new Bar();
        System.out.println(o.equals(o));

    }
}

class Foo {
    public boolean equals(Object o) {
        return this == o;
    }
}

class Bar  extends Foo{

}

Not sure if this is what you are looking for, but you can overload equals .

class Bar extends Foo{    
    public boolean equals(Bar b){
        return false;
    }
}

Why would you ever need to do this? I suppose you could with something like the following in Foo , but it breaks quite a few good design principles and could cause strange behavior later down the road if anyone else ever needs to use your code.

public final boolean equals(Object o) {
    return o.getClass() == Foo.class && this == o;
}

Note: This also breaks the contract for equals :

It is reflexive: for any non-null reference value x, x.equals(x) should return true.

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