The following blocks will help to understand the reference variable and de-referencing using java.
We have created Ball class with constructor and then created object with this class to understand the reference variables.
class Ball {
private String color;
public Ball(String color) {
this.color = color;
}
}
public class Main {
public static void main(String[] args)
Ball blueBall = new Ball(“blue”);
Ball anotherBall = blueBall;
Reference variable:
Here blueBall is a reference variable pointing to the new instance of class Ball (which has the parameter “blue”) and anotherBall is the copy of the reference blueBall . So, these two references are pointing to the same instance of the class.
Ball yellowBall = new Ball(“yellow”);
Now we have created another instance of the class Ball with parameter “yellow” and yellowBall is pointing to this instance.
So, we can see two instances are present here but three reference are associated with those two instances.
1st and 2nd—> pointing to the Ball instance consists of blue parameters.
3rd—> pointing to the Ball instance consists of yellow parameter.
De-referencing:
Ball greenBall=new Ball(“green”);
Ball anotherBall1=greenBall;
The reference variable anotherBall was already pointing to the Ball with blue parameter
but, now here we are de-referencing it and copying the greenBall reference to anotherBall.
So, now greenBall and anotherBall both are pointing to Ball with green parameter.
}
}