Reputation: 327
Consider a class named Calculator
with the following code:
class Calc extends Calculator {
Calculator calculator; // [Style 1]
Calculator calculator = new Calculator(); // [Style 2]
}
To my knowledge, no memory has been allocated in [1]
, but in statement [2]
a new Calculator
object is created.
Are there any other differences beyond that?
Upvotes: 2
Views: 4834
Reputation: 7694
When you write
Calculator calculator;
It only means that you're declaring a reference to the object of type Calculator
. Reference is not an object, so memory is not allocated.
When you write
new Calculator();
It constructs the object of type Calculator
and returns a reference to this object.
So, when you write
Calculator calculator = new Calculator();
It means that you construct the object and store a reference to it in calculator
.
'calculator' is not an object, it's only a reference to this object. You can have more than 1 reference to the same object.
Update: Regarding the title of this topic, creating the instance of class and creating the object are absolutely the same. What you mean is, I believe, declaring a reference to object vs declaring it with inplace assignment (though I'm not exactly sure about terms) :-)
Upvotes: 6
Reputation: 13501
Calculator calculator;
- its the definition of the variable calculator.. you tell the compiler that it can hold variable of type Calculator and nothing else. and it has null now and nothing is assigned..
Calculator calculator = new Calculator();--
this actually stores reference to Calculatore object created in heap to calculator variable. and now it stores a variable which is called initialisation.
Upvotes: 3
Reputation: 6499
Value of the first reference is null, and second one points to the objects. Also, if you have non-default constructor for Calculator class (with some side-effects, like logging, for example), it is not called in the first case.
Upvotes: 0
Reputation: 3024
In the first case, no object Calculator is created, and the value of the variable is null.
Upvotes: 2