Object References and Their Mechanisms
Object references
Variables that store the memory address of an object rather than the object itself.
Object references are like pointers in languages such as C++ or Golang, where variables can hold the address of primitive value or an object in memory.
Example- In Java, when you create an object using the new keyword, the variable holds a reference to the object:
Student student1 = new Student("Alice", 16);- Here, student1 is a reference to the Student object.
Sharing References and Modifying Objects
When you assign one object reference to another, both references point to the same object.
Examplepublic class Student{
public String name;
public int age;
public Student(String nameIn, int ageIn){
this.name = nameIn;
this.age = ageIn;
}
public static void main(String[] args){
Student student1 = new Student("Alice", 13); // initialise object
System.out.println("student1 initial name: " + student1.name + ", age: " + student1.age);
Student student2 = student1; // share reference
System.out.println("student2 initial name: " + student2.name + ", age: " + student2.age);
}
}
Changes made through one reference affect the object and are visible through other references.
Examplepublic class Student{
public String name;
public int age;
public Student(String nameIn, int ageIn){
this.name = nameIn;
this.age = ageIn;
}
public static void main(String[] args){
Student student1 = new Student("Alice", 13); // initialise object
System.out.println("student1 initial name: " + student1.name + ", age: " + student1.age);
Student student2 = student1; // share reference
System.out.println("student2 initial name: " + student2.name + ", age: " + student2.age);
// change student2 attributes
student2.age = 16;
student2.name = "Bob";
System.out.println("student2 new name: " + student2.name + ", age: " + student2.age);
System.out.println("student1 new name: " + student1.name + ", age: " + student1.age);
}
}
Null References
A reference that does not point to any object is called a null reference.
ExampleStudent student3 = null;Accessing methods or properties on a null reference will result in a runtime error (e.g., NullPointerException in Java).