Java Object Reference Variable

Description

Object reference variables act differently when an assignment takes place.

For example,


Box b1 = new Box(); 
Box b2 = b1; 

After this fragment executes, b1 and b2 will both refer to the same object.

The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same object as does b1. Thus, any changes made to the object through b2 will affect the object to which b1 is referring.

A subsequent assignment to b1 will simply unhook b1 from the original object without affecting the object or affecting b2.

For example:


Box b1 = new Box(); 
Box b2 = b1; 
// ... 
b1 = null; 

Here, b1 has been set to null, but b2 still points to the original object.

Example

Java Object Reference Variable

 
class Box {//w  w  w .j a  v  a  2  s  . c  om
  int width;
  int height;
  int depth;
}

public class Main {
  public static void main(String args[]) {
    Box myBox1 = new Box();
    Box myBox2 = myBox1;

    myBox1.width = 10;

    myBox2.width = 20;

    System.out.println("myBox1.width:" + myBox1.width);
    System.out.println("myBox2.width:" + myBox2.width);
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures