Reputation: 11
Please help me clear this confusion its bugging me alot. When I write the following code what happens in the memory and how is the object Jhon stored?(If I am correct that Jhon is an object and not merely a reference to an object)
class Human{
String Name;
float height;
}
class Student extends Human{
int Student_ID;
Student Jhon = new Student();
}
My question is, is Jhon an object or is it a reference to an object created? what is the reference variable here? What is an object variable here?
Upvotes: 0
Views: 61
Reputation: 140319
I'd say this is well-explained by the following line from JLS:
The value of a class instance creation expression is a reference to the newly created object of the specified class.
So, in the following code:
Student Jhon = new Student();
^-----------^ Class instance creation expression
^----------^ Variable declaration
To reiterate: the value of the class instance creation expression is the reference to a newly created object. That object is created somewhere in memory; but the key point is that the value isn't that object, but a reference to it.
And then you assign that reference to a variable, Jhon
. So Jhon
is not an object, nor a reference, but a variable whose value is a reference to a variable.
Upvotes: 2
Reputation: 1239
Just to add to @Andy Turner's response. Jhon is a variable that points to the reference to an instance of the class student that is held in the Java Virtual Machine (JVM) memory heap. The programmer has no way of directly accessing the object in the heap, that is all done by the JVM. The heap is managed by the JVM, when an object in the heap no longer has a variable that points to the reference to it, it will be cleaned up by the JVM garbage collection. The programmer does not have to concern themselves with this process.
See more detailed explanantion in official Oracle docs
Also see helpful disccusion in opening chapter of David Eck's book
Upvotes: 0