We already know how to create an object for a class.
Example - Box mybox = new Box( );
You can also create object by breaking the above line into two parts:
Example-
Box mybox;
mybox = new Box( );
Box is the class name
mybox is the object which will act as an instance of class Box
Box mybox;
Here 'mybox' object is declared as 'Box' class type. At this point mybox wont contain anything, i.e. it contains the value null.
mybox = new Box( );
This line allocates actual Box object and adds a reference to Box object to refer mybox.
new - The new operator dynamically assigns memory for Box object and adds a reference to Box object to refer mybox.
Box( ) - This is nothing but a constructor i.e. ClassName( ) . Constructors will be explained in the future posts.
Assigning an object's reference to another object -
Box box1 = new Box( ); //Create an object box1 for Box class and adding a reference to Box object to refer box1
Box box2 = box1; // copying the reference assigned to box1 to box2
Since we've copied the reference of box1 to box2 object, the both objects now will point to the same memory. So any changes made to the Box object through box2 will affect the Box object to which the box1 is reffering.
Lets implement this on Eclipse IDE by following the below steps -
1. Launch Eclipse IDE and ensure that 'Third Project' imported in our previous post is displayed as shown below:
2. Create another Class 'CopyBoxObject.java' with the code shown in the below screenshot -
3. Save and Run the 'CopyBoxObject.java' Class file and observe that the output is displayed as shown in the below screenshot -
Understanding the output -
As we've assigned the value of 100 to box1.height, but we have printed box2.height. box2.height has given output as 100.0 as both the objects are sharing the same value. i.e. The changes made to one object will automatically change the value of other object.
Download this program:
Click here to download this Project and try yourself by importing the project to the Eclipse IDE installed in your system.
Please comment below to feedback or ask questions.
How to use dot (.) operator will be explained in the next post.
1 comment:
Hi Arun,
Since box2 is defined before box1.height = 20. How box2.height will be assigned to 20? I executed the program and got output a 20. but still I am not convinced.
Can you pls help me in understanding the logic?
Box box2 = box1;
box1.height = 20;
Post a Comment