Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

java - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...