Provide Best Programming Tutorials

Java Object Reference Variable

Java Object Reference Variable

In this chapter you will learn:

  1. Assigning Object Reference Variables

  2. Example – 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 Demo.

 

 

class Box {
  int width;
  int height;
  int depth;
  public void sayHi(){
        System.out.println("Say Hi!");
  }
}

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

    myBox1.width = 10;

    myBox2.width = 20;
      
    myBox1.sayHi();

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

The code above generates the following result.

Leave a Reply

Close Menu