Advertisement
danysk

exact class check

Oct 22nd, 2019
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.71 KB | None | 0 0
  1. class Fragile {
  2.     public static void main(String... args) {
  3.       final var a = new A(0);
  4.       final var b = new B(0);
  5.       System.out.println("A equals B? " + a.equals(b));
  6.       System.out.println("B equals A? " + b.equals(a));
  7.     }
  8. }
  9.  
  10. class A {
  11.   protected final int n;
  12.   public A(int p) { n = p; }
  13.   public final int hashCode() { return n; }
  14.   public final boolean equals(Object other) {
  15.     if (other.getClass() == this.getClass()) {
  16.       return n == ((A) other).n;
  17.     }
  18.     return false;
  19.   }
  20. }
  21.  
  22. class B extends A {
  23.   public B(int p) { super(p); }
  24.   public int hashCode() { return n; }
  25.   public final boolean equals(Object other) {
  26.     return other instanceof B && n == ((B) other).n;
  27.   }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement