Difference between object reference declaration and object construction?

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?

-------------Problems Reply------------

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

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.

In the first case, no object Calculator is created, and the value of the variable is null.

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.

Category:java Views:0 Time:2011-08-18
Tags: java

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.178 (s). 11 q(s)