"Objects that are instances of an inner class exist within an instance of the outer class"
Even though I attempt to create an independent instantiation of the inner class, the outer class is always there because of the statement above.

Is that ture?

If true, then that would also mean the inner class holds a reference to the outer class. With the anonymous outer class, it (outer) would "live" until the inner class goes out of scope.

Yes?
AirJet.java
public class AirJet {
   public int model = 777;
   class Engine{
       public Engine() {
          model = 747;
       }
       public int getModel(){
          return model;
       }
   }
}
AirJetDemo.java
public class AirJetDemo {
   public static void main(String[] args) {
       // instantiation 1
       AirJet.Engine engine = new AirJet().new Engine();
       System.out.println("Model: " + engine.getModel());
  }
}

Recommended Answers

All 2 Replies

First a point of terminology: there's no such thing as an "anonymous outer class". Only inner classes can be anonymous.
Anyway, "yes" to both your questions. You have to create an instance of the outer class before you can create an instance of the inner class (unless the inner class is static, of course). An instance of an inner class has a reference to the outer class which it uses to access the members of the outer class, you can use that reference explicitly eg Airjet.this.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.