- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我对在实例上调用 new 的可能性感到困惑,比如
InnerClass sc = pc.new InnerClass();
我知道如何使用它,但我的问题是关于完全理解它。喜欢:
JAVA文档中哪里有描述?
这是应该使用的推荐解决方案,还是有更好的方法?
为什么普通的"new"不起作用?
我在一个代码示例中看到了它,并且我已经了解了我无法在静态上下文中使用普通的“new”。
这是作为可运行示例的完整上下文:
class ParentClass{
ParentClass(){
}
public static void main(String[] args){
ParentClass pc = new ParentClass();
InnerClass sc = pc.new InnerClass();
}
class InnerClass {
InnerClass() {
System.out.println("I'm OK");
}
}
最佳答案
免责声明:您在示例中使用的术语“父类”和“子类”不正确,因此我下面的示例将使用正确的术语“外部类”和“内部类” (感谢@eis 的提示)。
Where is it described in the JAVA documentation?
查看@eis 对我的回答的评论以获取链接。
Is this a recommended solution that should be used, or is there a better way?
这取决于 – 取决于您需要它做什么。如果 SubClass
不需要 ParentClass
的instance 的任何信息,它可以(并且应该)被设为静态或提取为非根本不再是一个内部类。在这种情况下,您可以在没有 ParentClass
实例的情况下直接调用 new
。
Why doesn't a plain "new" work?
因为SubClass
可能会引用周围实例的信息,这需要你指定那个实例。从扩展 ParentClass
的意义上说,它不是子类,而是它的类型成为外部类的成员。
考虑一下(并查看它的实际效果 here ):
public class OuterClass {
private int field;
public OuterClass(int field) {
this.field = field;
}
class InnerClass {
public int getOuterClassField() {
// we can access the field from the surrounding type's instance!
return OuterClass.this.field;
}
}
public static void main(String[] args) throws Exception {
OuterClass parent = new OuterClass(42);
// prints '42'
System.out.println(parent.new InnerClass().getOuterClassField());
// cannot work as it makes no sense
// System.out.println(new InnerClass().getOuterClassField());
}
}
如果您能够简单地执行 new InnerClass()
,则无法知道 getOuterClassField
应该返回什么,因为它连接到 实例 它周围的类型(而不仅仅是类型本身)。
关于java - 在实例上调用 new,比如 pc.new InnerClass()——这是怎么回事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28515553/
我是一名优秀的程序员,十分优秀!