interpretation of the statement in java
https://softwareengineering.stackexchange.com/questions/288253
-
09-10-2020 - |
Question
I am confused over the interpretation of the following statement
Fruit x= new Fruit();
My interpretation is that the new
operator along with Fruit();
creates a new object somewhere in the memory.
Now x
is a reference variable that points toward the object created and if I write Fruit x
, does it only mean that a reference variable is created which points no where?
Can i also say that x
keeps the memory location of the object?
Solution
You are absolutely correct.
new
operator reserves space in memory for a new object of Type Fruit. Assignment =
assigns the reference to your variable x
.
If you were to write Fruit y = x;
, you would only create a new reference, so both y
and x
would still be pointing to single location on memory.
For more in-depth knowledge, check out this article.
OTHER TIPS
The statement Fruit x = new Fruit();
creates a new object belonging to the class Fruit and x
stores a reference to that object.
More specifically, when the computer executes this statement, it allocates memory to hold a new object of type Fruit. It calls a constructor, which can initialize the instance variable of the object as well as perform other tasks. A reference to the new object is returned as the value of the expression "new Fruit()".
Finally, the assignment statement stores the reference in the variable x. So, x can now be used to access the new object.