Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Wiki Markup
"There is simply no way to extend an instantiable class and add an aspect while preserving the equals contract." This implies that composition must be preferred over inheritance in this case. \[[Bloch 08|AA. Java References#Bloch 08]\] This is done by giving the {{XCard}} class a private {{card}} field and providing a a public {{viewCard}} method. \[[Bloch 08|AA. Java References#Bloch 08]\]

Code Block
bgColor#ccccff
public class Card {
  private final int number;

  public Card(int number) {
    this.number = number;
  }

  public boolean equals(Object o) {
  if (!(o instanceof Card))
    return false;
    Card c = (Card)o;
    return c.number == number;
  }
}

class XCard extends Card {
  private String type;
  private Card card;
  
  public XCard(int number, String type) {
    super(number);
    this.type = type;
  }
	  
  public Card viewCard() {
    return card;
  }

  public boolean equals(Object o) {
    if (!(o instanceof XCard))
      return false;
      
      XCard cp = (XCard)o;
         return cp.card.equals(card) && cp.type.equals(type);
  }
	  
  public static void main(String[] args) {
    XCard p1 = new XCard(1, "type1");
    Card p2 = new Card(1);
    XCard p3 = new XCard(1, "type2");
    System.out.println(p1.equals(p2)); //returns false
    System.out.println(p2.equals(p3)); //returns false
    System.out.println(p1.equals(p3)); //returns false
  }
}

Wiki Markup
"There are some classes in the Java platform libraries that do extend an instantiable class and add a value component. For example, java.sql.Timestamp extends java.util.Date and adds a nanoseconds field. The equals implementation for Timestamp does violate symmetry and can cause erratic behavior if Timestamp and Date objects are used in the same collection or are otherwise intermixed." \[[Bloch 08|AA. Java References#Bloch 08]\]

Risk Assessment

Violating the general contract when overriding the equals() method can lead to unexpected results.

...