if i call foo() ,new instance of Chassis is created as a parameter an engine object,and the reference of the new object created also remains outside method right?
for example:
if i call method print() after calling foo() it will print the memory address of the new object Chassis created?
Yes as far as both method will be invoked on the same instance of Car, You can try that.
chassis
is an instance field of Car
class, and inside foo()
method, you are creating an instance of Chassis
and assign it to instance field chassis
if i call doSomething() a new Engine is created and immediately i call setEngine, and in this case, the engine "pointer" of the class car points to the new instance I created:
The old engine "pointer" is carbage collected And now the reference is the new instance created and if I call back foo, a new chassis is created with a new instance of the engine?
Bit correction there, reference are not Garbage Collected, only object are Garbage Collected. When you assign a object to a reference, the previous object will be GGed, if it doesn't have any live reference.