Originally posted by Bala Krishniah:
MyClassObject method()
{
MyClassObject myObject = new MyClassObject();
:
:
return myobject;
}
In my main, can I assign this return type to new object like this...
(1)MyClassObject myOtherObject1 = method();
(2)MyClassObject myOtherObject2 = new MyClassObject();
myOtherObject1 = method();
Which one is correct?
In the first case, you are invoking a method which initialises the object
myOtherObject1 . In the second case, you are creating a new object and assigning it to
myOtherObject2 Then you are assigning it to a different object via method() method. So now, your reference
myotherObject1 points to a different object created by
method() and the object , it initially referred, is now dangling(assuming that without any active reference to it, it would be garbage collected).
The approach suggested in case 1 is better than case 2 since it involves a lower number of object creation.So the bottom line is, it is not a rule that
you should explicitly use
new keyword to create and initialise an object, as long as your object reference points to the initialised object(which can be assigned to its reference type). This can either be done by a new keyword or through any other approach which assigns the object reference to an already created/initialised object.
[This message has been edited by Sowmya Vinay (edited February 19, 2001).]