Java OOP · Module 2
References and aliasing
Why two variables can secretly be one object
What you'll be able to do
- Explain what a reference variable actually stores
- Predict the result when two variables point at one object
- Say what happens to an object passed into a method
- Use == and .equals() for the right question
Object References
A variable holds an address, not the object
This single idea explains half of the confusing bugs beginners hit — and it is a favourite interview question.
Two remotes, one television
Give a friend a second remote control for your TV. Now there are two remotes but still one television: whoever presses volume-up, *your* TV gets louder. Reference variables are remotes; the object is the TV. Tv b = a; hands out a second remote — it does not buy a second TV.
Aliasing, line by line
a stores its address.b. There is only one volume in existence.After `Tv b = a;` and two turnUp() calls
Two stack slots, one heap object. Nothing was duplicated.
Passing an object into a method
Java always passes by value — but for objects the value being copied is the reference. So the method receives its own remote pointing at your object: changes to the object's *fields* are visible to you, while reassigning the parameter (box = new Box();) only repoints the method's local remote and changes nothing outside.
== vs .equals() — pick the right question
a == b asks *same object?* — useful for identity checks and for x == null. a.equals(b) asks *equivalent content?* — and it only behaves sensibly if the class defines what equality means. For your own classes without an equals method, both end up comparing identity.
Predict all three lines first. Then add `b = new Tv();` before the prints and see which lines change.
Prove it — coding challenges
Common mistakes
Tv b = a; // now I have two TVsif (student1 == student2) { /* same name? */ }static void replace(Box box) { box = new Box(); }Lesson playground
Two remotes, one TV. Change `b = a;` into `b = new Tv();` and watch every printed line change meaning.
Check understanding
Quiz
Question 1 of 4
One method mutates the object, the other reassigns the parameter. What is printed?
Summary
- A reference variable stores an address; the object lives on the heap.
- Assigning one reference to another creates an alias — one object, two names.
- Methods receive a copy of the reference: field changes are visible outside, reassignment is not.
- `==` asks 'same object?'; comparing content means comparing fields.