How do I create an instance of a inner class in the outer class constructor

I switched from C++ to Java and have a problem with nested classes. I would like to initiate an instance of a subclass in the constructor of the superclass. I tried it like this, but it seems to be wrong.

public class Aircraft {
    public class LandingGear {
    }

    public Aircraft() {
        Aircraft.LandingGear myLandingGear = this.new LandingGear();
    }
}

The idea is that every instance of the class Aircraft has an instance “myLandingGear” of the subclass LandingGear.

Answer

Every Aircraft will have a LandingGear

public class Aircraft {
    private LandingGear myLandingGear;


    public Aircraft() {
        myLandingGear = new LandingGear();
   }

   public LandingGear getLandingGear() {
       return this.myLandingGear;
   }

}

Leave a Reply

Your email address will not be published. Required fields are marked *