OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 3 : Assigning One Object to Another

 Unit - 2

Topic 3 : Assigning One Object to Another in Java

In Java, when you assign one object reference to another, you are not creating a new object. Instead, both references will point to the same object in memory.


How It Works

Example:

Box b1 = new Box(); // Create a new Box object Box b2 = b1; // Assign b1 to b2

At this point:

  • No new object is created when assigning b1 to b2.

  • Both b1 and b2 refer to the same memory location.

  • Any changes made through b1 will also be visible when accessing through b2 (and vice versa).




Visualization in Memory

Before Assignment: b1 [Box Object #1] b2 null After: b2 = b1; b1 [Box Object #1] ← b2

Example Program

class Box { double width; double height; double depth; void volume() { double vol = width * height * depth; System.out.println("Volume is " + vol); } } public class ObjectReferenceDemo { public static void main(String[] args) { Box b1 = new Box(); b1.width = 10; b1.height = 20; b1.depth = 15; Box b2 = b1; // b2 now refers to the same object as b1 System.out.println("Volume using b1:"); b1.volume(); System.out.println("Volume using b2:"); b2.volume(); // Change values using b2 b2.width = 5; b2.height = 6; b2.depth = 7; System.out.println("After modifying via b2:"); // Check values through b1 b1.volume(); // Check values through b2 b2.volume(); } }

Sample Output

Volume using b1: Volume is 3000.0 Volume using b2: Volume is 3000.0 After modifying via b2: Volume is 210.0 Volume is 210.0

Key Takeaways

  • Object variables in Java hold references, not actual object data.

  • Assigning one reference to another makes them point to the same object.

  • Any changes via one reference affect the same underlying object.

  • To make an actual copy, you need to create a new object and copy the values manually (or use cloning).

Comments

Popular posts from this blog

Career Guide - B.Tech Students

Artificial Intelligence - UNIT - 1 Topic - 1 : Introduction to AI (Artificial Intelligence)

Financial Aid for Students: Scholarships from Government, NGOs & Companies