[英]Why can't object of nested class be used as a parameter of supertype constructor?
I have code like the following: 我有如下代码:
class A {
final Object data;
A(Object _data) {
data = _data;
}
class B extends A {
B() {
super(new C());
}
class C { }
}
}
I get following error message: 我收到以下错误消息:
Cannot reference 'C' before supertype constructor has been called
I don't understand why it is not possible. 我不明白为什么这不可能。
Are there any workarounds? 有什么解决方法吗? I want
data
to be final and classes to be nested as they are in the code above (I don't want to create a different file for each class, because classes are quite small and in my real code it would be more logical for them to be nested) 我希望
data
是最终的,类要像上面的代码中那样嵌套(我不想为每个类创建一个不同的文件,因为类很小,而在我的实际代码中,它们对它们来说更合逻辑嵌套)
With a simple nested class, it would be fine. 使用简单的嵌套类,就可以了。 However, you're creating an inner class of
B
, which means you're implicitly passing a reference to an instance of B
- which would be this
in this case, and you can't use this
before super(...)
completes. 但是,你要创建一个内部类的
B
,这意味着你隐式传递一个参考的实例B
-这将是this
在这种情况下,你不能使用this
之前super(...)
完成。
Here's another example - read the comments: 这是另一个示例-阅读评论:
class Base {
Base(Object x) {}
}
class Outer extends Base {
Outer() {
super(new Nested()); // No problem
}
Outer(int ignored) {
super(new Inner()); // Effectively this.new Inner()
}
Outer(boolean ignored) {
super(new Outer().new Inner()); // Fine
}
Outer(long ignored) {
super(new Nested(this)); // Explicitly passing this
}
static class Nested {
Nested() {}
Nested(Object ignored) {}
}
class Inner {
}
}
The problem is that non-static inner classes need an instance of the outer class before they can be instantiated. 问题在于,非静态内部类在实例化之前需要外部类的实例。 That's why you can even access fields of the outer class directly in the inner class.
这就是为什么您甚至可以直接在内部类中访问外部类的字段的原因。
Make the inner classes static
and it should work. 使内部类
static
,并且应该可以工作。 In general it's a good pattern to use static inner classes instead of non-static. 通常,使用静态内部类而不是非静态内部类是一个很好的模式。 See Joshua Bloch's Effective Java item 22 for more information.
有关更多信息,请参见Joshua Bloch的Effective Java项目22。
class A {
final Object data;
A(final Object _data) {
data = _data;
}
static class B extends A {
B() {
super(new C());
}
static class C {
}
}
}
Hi sorry could not leave a comment. 您好,抱歉无法发表评论。
I don't want to create a different file for each class, because classes are quite small
我不想为每个类创建一个不同的文件,因为类很小
I had a professor that always said "There are never too small classes, only too big ones" 我有一位教授总是说: “永远不会有太小的班级,只有太大的班级”
If you persist and still want the classes to be nested you can make class C static depending on your purpose of course. 如果您坚持并仍然希望嵌套类,则可以根据您的目的将C类静态化。 But I highly recommand to question your design.
但我强烈建议您质疑您的设计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.