Question: Consider the following (textbook) code: public class User { private String name; public User (String name) { this.name = name; } @Override public boolean equals
Consider the following (textbook) code:
public class User { private String name; public User (String name) { this.name = name; } @Override public boolean equals (Object obj) { if (!(obj instanceof User)) return false; return ((User) obj).name.equals(this.name); } } public class SpecialUser extends User { private int id; public SpecialUser (String name, int id) { super(name); this.id = id; } @Override public boolean equals (Object obj) { if (!(obj instanceof SpecialUser)) return false; return super.equals(obj) && ((SpecialUser) obj).id == this.id; } } 1.
(a) What does it mean for the equals() method to be correct? How do you know? Be as concrete as you can. Can you check correctness with test cases?
(b) How does the given implementation of equals() in in class User stack up? Again, be concrete. Can you find a test case that demonstrates the problem?
(c) How does inheritance complicate the correctness discussion for equals() in class SpecialUser?
(d) What do you think of the equals() method in the SpecialUser class?
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
