質問

look at this example:

Class Car{
  private Chassis  chassis;
  private Engine engine;

  public Car(Engine engine){  //passing a object that is instantiated outside the class
    this.engine = engine;       
  }

  public void foo(){
      chassis = new  Chassis(engine);
  }
  public void print(){
     System.out.println(chassis);
  }

  public setEngine(Engine engine){
     this.engine = engine;    
  }
 }

class CarPark{
 private Car car;

 public CarPark(Car car){
    this.car = car;

 }     
public void doSometing(){
    Engine engine = new Engine();
    car.setEngine(engine);
 }

}

some considerations :

  • 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?

  • 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?

all these considerations are correct?

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top