class A {
int a = 1;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof A)) return false;
A a1 = (A) o;
return a == a1.a;
}
}
class B extends A {
int b = 1;
@Override
public boolean equals(Object o) {
if (this == o) return true;
// Ошибка - нарушен принцип подстановки Барбары Лисков
// if (o == null || getClass() != o.getClass()) return false;
if (!(o instanceof A)) return false;
if (!super.equals(o)) return false;
if(o instanceof B) {
B b1 = (B) o;
return b == b1.b;
}
return true;
}
}
@Test
public void testEquals() {
A a = new A();
B b = new B();
System.out.println(a.equals(b)); // true
System.out.println(b.equals(a)); // true
}
//..
if (!(o instanceof A) {
return false;
}
if (!(o instanceof B)) {
return this.equals(o);
}
//..
There is no way to extend an instantiable class and add a value component while preserving the equals contract