SWE 619 In Class Exercise Number 6A


This exercise is from one of the reading reflections. Thx!

public final class Person implements Comparable {
    // What are the rep-invaraints for the different variations?
    private final int age;
    private final String name;
    // private final int id;   // does this help?
    public Person (int age, String name) {
       if (name == null) throw new NullPointerException(); // simplify equals()
       this.age = age;  // no defensive copy needed
       this.name = name;  // no defensive copy needed
    }
    @Override public boolean equals (Object obj) {
       if (!(obj instanceof Person)) return false;
       Person p = (Person) obj;
       return (p.age == this.age) && (p.name.equals(this.name));
       // return p.id == this.id;   // is this better?
    }
    @Override public int compareTo (Person p) {
       return this.age - p.age;   // is this consistent with equals()?
       // Does adding something about names help?
       // What about an id field?  How does that change things?
    }
    // other methods omitted
}

Work through the variations!