Google+

178. Assigning 'Object Reference' variables







We can assign the object reference of the variable that is defined of the Class type to another variable that is defined of the same Class type as shown below -

1. Lets define a variable benz as Car Class type and assign an object's reference to the defined variable as shown below -

Car benz;  //Defined a variable benz as Car Class type
benz = new Car( );   //Assigned the objects reference to the Car Class defined variable benz.

2. Now define another variable audi as Car Class type as shown below -

Car audi;  //Defining a variable audi as Car Class type

3. Now assign the object reference of the benz variable to the audi variable as shown below -

audi = benz;   //Assigning the object reference of benz variable to audi variable

At this point, the variables benz and audi locate to the same objects reference as shown below -


4. As both the variables benz and audi are referring to the same object, they will be referring to the same instance variables and methods. So, any changes made to the object through benz variable will affect the object to which audi is referring.

Lets implement this on Eclipse IDE -

1. Launch Eclipse IDE, create a Java Project 'Project 018' as shown below -



2. Create a Class named Car with the following code as shown below -


3. Create another Class say One and declare and create an object reference for the benz variable as shown below -



4. Define another variable audi as Car Class type as shown below -



5. Assign the object reference of benz variable to audi variable as shown below -



6. Now assign the integer values to the instance variable of Car Class object by accessing it using benz variable as shown below -


7. Now print the instance variables of the Car Class object by accessing it using audi instead of benz as shown below -


8. Save and Run the One Class and observe that the values assigned to the object via benz variable are displayed, though we have printed the value of  the object via audi variable -


Since the variable of Car Class type i.e. benz and audi are locating to the same object, the values assigned to to the instance variables via benz are same as the values displayed in the output via audi.




Please comment below to feedback or ask questions.

Data Types in Java will be explained in the next post.




No comments: