Reputation: 370
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{
}
Upvotes: 1
Views: 101
Reputation: 44808
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.
Upvotes: 1
Reputation: 93842
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;
}
}
Upvotes: 3