Menu
Topics Index
...
`


Classes >
Siva Nookala - 12 Apr 2016
Class References and Objects - Example

Class References and Objects
class ReferencesAndObjects
{
    public static void main(String s[])
    {
        Student st1 = new Student(); // Object STUDENT_RAJESH
        Student st2;
        st2 = st1;
    
        st1.name = "Rajesh";
        st2.marks = 87;
        st1.section = 'C';
    
        System.out.println("Print using st1 : " + st1.name + " " + st1.marks + " " + st1.section);
        System.out.println("Print using st2 : " + st2.name + " " + st2.marks + " " + st2.section);
    
    }

}

class Student
{
    String name;
    int marks;
    char section;
}
OUTPUT

Print using st1 : Rajesh 87 C
Print using st2 : Rajesh 87 C

DESCRIPTION

As we can see here, we have created only one Student object, but have two references st1 and st2. Both st1 and st2, point to the same object, so changes done using one reference are visible when accessed through the other reference. That is why, even though the name and section are assigned using st1 and marks are assigned using st2, when the details are printed using st1 or using st2, the output Rajesh 87 C is the same.

THINGS TO TRY
  • Create a new reference st3 and assign reference st1 to it like Student st3 = st1;. Print the details using st3 and see that the output is the same as the STUDENT_RAJESH.
  • Create a new reference st4 and assign it to null. i.e. Student st4 = null;. When you try to print the details of st4, it fails with NullPointerException since st4 does not point to any object.
  • Create a new reference and a new object STUDENT_MAHESH using Student st5 = new Student();. Using the reference st5, assign values "Mahesh", 88, 'A' to the variables name, marks and section respectively. Now print the details of the new student using the reference st5. See that the details of object STUDENT_MAHESH are printed. Also observe that the details of st1 and st2 still remain as is and are not impacted.

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App