Unit 3 Cycle 1 Day 23: Comparing Two Objects of Same Class
Share
Comparing Two Objects of Same Class
Section 3.10 — The this Keyword
Key Concept
Methods that compare the current object to another object of the same class use this and a parameter. A method like boolean isOlderThan(Person other) compares this.age to other.age. Inside the method, this refers to the object the method was called on, and other refers to the argument. Since both are the same class, the method can access both objects' private fields directly. The AP exam tests this pattern in methods that find the larger, older, or better of two objects.
Consider the following class.
What does the following code print?Box a = new Box(10); Box b = new Box(20); System.out.println(a.larger(b) == b);
Answer: (A) true
a.larger(b): this=a(10), other=b(20). isLargerThan: 10>20 is false. Returns other (b). b == b is true (same reference).
Why Not the Others?
(B) The larger method returns the other Box (b), and b == b compares the same reference.
(C) The method returns a Box object, not an int.
(D) Methods can return this or other objects. This is valid.
Common Mistake
When a method returns other, it returns the actual reference passed in. So a.larger(b) returns the same object that b points to, making == b true.
AP Exam Tip
Methods that return this or a parameter reference return the actual object reference, not a copy. == will be true if compared to the same variable.