Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate inner class object from current outer class object

I am wondering if the following is valid in Java:

class OuterClass {

    OuterClass(param1, param2) {
        ...some initialization code...
    }

    void do {
       // Here is where the doubt lays
       OuterClass.InnerClass ic = this.new InnerClass();
    }

    class InnerClass {

    }

}

Basically what I am trying to achieve here is to instantiate an inner class object from the current instance of the outer class, not a new instance, the current one. I believe this comes handy is when the constructor of the outer class is not empty (takes parameters) and we don't know what pass to them (they can't be null since some might be assigned to a class variable that is accessed by the inner class object).

Let me know if I explained myself well.

Thanks in advance!

like image 455
romeroqj Avatar asked Dec 06 '22 18:12

romeroqj


2 Answers

Regarding:

public class OuterClass {

   OuterClass() {
       // ...some initialization code...
   }

   void doSomething() {
      OuterClass.InnerClass ic = this.new InnerClass();
   }

   class InnerClass {

   }

You don't need the explicit OuterClass identifier nor the this as they're implied.

So this is unnecessary:

OuterClass.InnerClass ic = this.new InnerClass();

And this is fine inside of an instance method:

InnerClass ic = new InnerClass();

Things get dicier though if you're creating an object of InnerClass in a static method such as main that is held inside of OuterClass. There you'll need to be more explicit:

This won't work

public class OuterClass {
    public static void main(String[] args) {
       InnerClass otherInnerVar = new InnerClass(); // won't work
    }

But this will work fine:

public class OuterClass {
    public static void main(String[] args) {
       InnerClass otherInnerVar2 = new OuterClass().new InnerClass(); // will  work
    }
like image 183
Hovercraft Full Of Eels Avatar answered Apr 22 '23 11:04

Hovercraft Full Of Eels


Every instance of an inner class, unless the Class is declared as static, must have a 'connected' instance of an outer class, in order to be instantiated.

This won't work:

public class Outer {
    public class Inner { 
    }
    public static void main(String[] args) {
        Inner inner = new Inner(); //compilation error
    }
}

However, this will work, it doesn't need an instance of Outer, since the static keyword is used:

public class Outer {
    public static class Inner { 
    }
    public static void main(String[] args) {
        Inner inner = new Inner(); 
    }
}

more info: java inner classes

like image 33
amit Avatar answered Apr 22 '23 12:04

amit