Object and Reference variable


Most of us think that the object and reference variable is the same thing.
Observe the below code :
Student s = new Student();
Now if you know object oriented programming(oop) then identify the object from the above code. Most of us are guessing it the same. Those who are thinking that s
is the object of class Student
then this blog is for you only.
Let us first breakdown the code :
Student
is the class.s
is the reference variable not an object, holds the address of object from heap.new
is the keyword which allocates the memory for an object in heap.Student()
is constructor called to initialize the object .
We can run the code fine and access the data members like methods and variables without creating a reference from the class. Look at the below code:
new Student().method();
new Student().rollNo = 6;
Here new Student();
will create an object in heap memory. Now you might be thinking that then why we need the reference then, we continue with object only. Here is answer :
If we not create the reference pointing to object then stored in memory vanishes as soon as its task completed. But we want that object further in use. Hence for that we need a reference variable.
Hence object can exist without a class.
Can reference exist without a class?
Let us observe the first code again. There is reference variable s
of class Student
. Reference variable holds the address of object. Reference variable scope is at block level or local. Hence it is stored in the stack memory. Whenever we are calling the reference variable then that reference variable from stack point to object in heap memory. For every reference variable the separate copy of object is created.
Student s;
The above code will work fine but we cannot access data members from the class because there is no object here. And if we try to do so then at first we have to initialize the reference as null. Then if we are trying to access the data member of the class then we will get a run time exception NullPointerException
Subscribe to my newsletter
Read articles from Aditya Gaikwad directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
