Assigning Object Reference Variables : 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 –
Box b1 = new Box(); Box b2 = b1;
- b1 is reference variable which contain the address of Actual Box Object.
- b2 is another reference variable
- b2 is initialized with b1 means – “b1 and b2” both are referring same object , thus it does not create duplicate object , nor does it allocate extra memory.
Example : Assigning Object Reference Variables
class Box { double width; double height; } class BoxExample { public static void main(String args[]) { Box b1 = new Box(); Box b2 = b1; b1.width = 10; b2.height = 20; System.out.println("Value of Box1's Height : " + b2.height); System.out.println("Value of Box2's Height : " + b2.height); } }
Output :
C:Zubair>java BoxExample Value of Box1's Height : 20.0 Value of Box2's Height : 20.0
Concept :
Suppose we have assigned null value to b2 i.e
Box b1 = new Box(); Box b2 = b1; . . . b1 = null;
Note : Still b2 contain reference to an object. Thus We can create have multiple reference variables to hold single object.
This is a great blog. Enjoyed it thoroughly. java training in chennai
ReplyDelete