The material is intended to supplement the textbook by providing further examples and discussion. It is not self-standing, but assumes that you have a copy of the book to hand.
class Person {
private String name;
public Person(String n) {
name = n;
} // constructor
public String getName() {
return name;
} // getName
public boolean equals(Person p) {
return name.equals(p.getName())
} // equals
}
Define a class Student that inherits from Person,
but which has an extra String attribute regNum
and a method getRegNum.
We now want to override the method equals
to determine if two objects refer to the same Student, i.e.
that they have the same regNum.
Why can we not do this? The following declarations and statements may help.
Person p1 = new Student("Jim", "316-2");
Person p2 = new Student("Mary", "417-3");
Person p3 = new Person("Jo");
if (p1.equals(p2)) { ... }
if (p1.equals(p3)) { ... }