从当前外部类对象实例化内部类对象
我想知道以下内容在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 {
}
}
基本上,我在这里试图实现的是从外部类的当前实例实例化一个内部类对象,而不是一个新实例,而是当前实例。我相信当外部类的构造函数不为空(带有参数)并且我们不知道传递给它们的内容时(它们不能为空,因为有些可能被分配给由内部类对象)。
如果我很好地解释了自己,请告诉我。
提前致谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
关于:
您不需要显式的 OuterClass 标识符,也不需要隐含的 this 。
所以这是不必要的:
这在实例方法内部很好:
但是,如果您在静态方法(例如 OuterClass 内部保存的 main)中创建 InnerClass 对象,事情会变得更加危险。在那里你需要更明确:
这不会起作用
但是这会很好地工作:
Regarding:
You don't need the explicit OuterClass identifier nor the this as they're implied.
So this is unnecessary:
And this is fine inside of an instance method:
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
But this will work fine:
内部类的每个实例(除非该类被声明为
static
)都必须有一个外部类的“连接”实例才能被实例化。这行不通:
但是,这行得通,它不需要
Outer
的实例,因为使用了static
关键字:更多信息:java内部类
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:
However, this will work, it doesn't need an instance of
Outer
, since thestatic
keyword is used:more info: java inner classes
上面是在外部类内部和外部类外部创建内部类对象的示例:
Above is the example for creating Inner class object inside outer class and outside outer class: