从当前外部类对象实例化内部类对象 [英] Instantiate inner class object from current outer class object

查看:184
本文介绍了从当前外部类对象实例化内部类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道以下是否在Java中有效:

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 {

    }

}

基本上我在这里要实现的是从外部类的当前实例实例化内部类对象,而不是新实例,即当前实例。我相信这很方便,因为外部类的构造函数不为空(接受参数)而我们不知道传递给它们的是什么(它们不能为null,因为有些可能被分配给一个由内部类对象)。

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.

提前致谢!

推荐答案

关于:

public class OuterClass {

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

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

   class InnerClass {

   }

您不需要显式的OuterClass标识符,也不需要它们,因为它们是隐含的。

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

所以这是不必要的:

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

这在实例方法中很好:

InnerClass ic = new InnerClass();

如果您在静态方法(例如main)中创建InnerClass的对象,那么事情会变得更糟糕在OuterClass里面。在那里你需要更明确:

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:

这不起作用

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

但这样可以正常工作:

public class OuterClass {
    public static void main(String[] args) {
       InnerClass otherInnerVar2 = new OuterClass().new InnerClass(); // will  work
    }

这篇关于从当前外部类对象实例化内部类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆