Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between object reference declaration and object construction?

Tags:

java

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?

like image 693
BoomirajP Avatar asked Feb 06 '26 15:02

BoomirajP


2 Answers

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) :-)

like image 169
Andrey Agibalov Avatar answered Feb 09 '26 05:02

Andrey Agibalov


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.

like image 25
ngesh Avatar answered Feb 09 '26 05:02

ngesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!