Solution being the name of the class, what is the difference between the following?
Solution solution;
Solution solution = new Solution();
Solution being the name of the class, what is the difference between the following?
Solution solution;
Solution solution = new Solution();
There are three steps in object declaration and assignment in Java
Solution solution
You're telling Java to allocate space for a new reference variable.
This variable will be forever of type Solution
and it's only purpose is to
hold the reference to an object of type Solution
.
But we haven't created that object yet, have we?
solution = new Solution();
The creation of the object. Java allocates space for the new object and creates it. That includes space for any variables that come along with the object (it's instance variables)
solution =
new Solution();
We're assigning the reference variable to the newly created object (note the equals sign).
In other words that reference variable will be connected with that object from now on and we can use that reference to call methods on it.
Note that the last two steps are one line of code, but there's actually two different steps happening here.
what is the difference between the following?
Solution solution
created an empty reference, a variable waiting for an object to be assigned to it.
Solution solution = new Solution()
did all three steps in one line of code.
It created the reference, created the object and connected them together.
You can read more about the memory allocation in Java and programming in general here:
Where are instance variables of an Object stored in the JVM?
Solution solution;
only defines that solution
variable is a Solution
but it is otherwise uninitialized
Solution solution = new Solution();
also initializes it as an instance of Solution