Java assigning object reference
Contents
Assigning Object Reference Variables : Class Concept in Java Programming
- We can assign value of reference variable to another reference variable.
- Reference Variable is used to store the address of the variable.
- Assigning Reference will not create distinct copies of Objects.
- All reference variables are referring to same Object.
Assigning Object Reference Variables does not -
- Create Distinct Objects.
- Allocate Memory
- Create duplicate Copy
Consider This Example -
Rectangle r1 = new Rectangle(); Rectangle r2 = r1;
- r1 is reference variable which contain the address of Actual Rectangle Object.
- r2 is another reference variable
- r2 is initialized with r1 means - “r1 and r2” both are referring same object , thus it does not create duplicate object , nor does it allocate extra memory.
Live Example : Assigning Object Reference Variables
class Rectangle { double length; double breadth; } class RectangleDemo { public static void main(String args[]) { Rectangle r1 = new Rectangle(); Rectangle r2 = r1; r1.length = 10; r2.length = 20; System.out.println("Value of R1's Length : " + r1.length); System.out.println("Value of R2's Length : " + r2.length); } }
Output :
C:Priteshjava>java RectangleDemo Value of R1's Length : 20.0 Value of R2's Length : 20.0
Typical Concept :
Suppose we have assigned null value to r2 i.e
Rectangle r1 = new Rectangle(); Rectangle r2 = r1; . . . r1 = null;
Note : Still r2 contain reference to an object. Thus We can create have multiple reference variables to hold single object.
[468x60]