0

Lets say I have an outer class called 'Foo' and inside 'Foo' class I have a nested inner class called 'Bar'. Now inside 'Bar' class I have another inner called 'Choo'.

What I want to do is create an instance of 'Choo' class from a method inside outer class 'Foo', for example take the below code:

public class Foo {

   // Other class fields

   private class Bar {

      // Other class fields

      private class Choo {
      
      // Other class fields

      }
   }

   public void createChooObject() {

      // Tried this but doesn't work
      Bar.Choo theChooObject = new Bar.Choo();

      // Also tried this but doesn't work
      Bar.Choo theChooObject1 = Bar.new Choo();

   }

}

Is this somehow possible or do I have to declare a method inside inner class 'Bar' a method which creates and returns the 'Choo' object?

Jos
  • 11
  • 5
  • There is no difference between a "first level" or "second level" inner class. As these are **non static** classes, you need an instance of the *outer* class to create the inner object from. So you first need to create a Foo instance, then create a Bar instance, then you can create a Choo() instance. – GhostCat Mar 15 '22 at 14:17
  • 1
    Your code tries to use the syntax for static inner classes more or less. (and just saying: nesting 3 levels down is awkward, that is something you probably wouldnt do in real world code) – GhostCat Mar 15 '22 at 14:18
  • From a static context (and wherever you don't want to use the current instance), you'd be forced to write `new Foo().new Bar().new Choo()`. But You can reduce that to `new Bar().new Choo()` in your code, because the "current" instance will do as a `Foo`. – ernest_k Mar 15 '22 at 14:19
  • @GhostCat First of all thanks for the answers. So in sort I can't really create an object of the second level inner class without defining a Foo object, unless the inner classes are static right? – Jos Mar 15 '22 at 14:25

0 Answers0