返回信息流最近看书中间有这么一个题
public class Thing {
public Thing(int i) { ... }
...
}
public class MyThing extends Thing {
private final int arg;
public MyThing() {
super(arg = SomeOtherClass.func());
...
}
}
其中SomeOtherClass.func()是调用另一个返回int型的函数
但是这样编译报错
MyThing.java:
can't reference arg before supertype constructor has been called super(arg = SomeOtherClass.func());
不明白为什么这样写是错误的,请教一下各位。谢谢!
这是一条镜像帖。来源:北邮人论坛 / java / #18561同步于 2011/5/30
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
子类的构造函数
ValensZC
2011/5/30镜像同步5 回复
订阅后,新回复会通过你的通知中心匿名送达。
5 条回复
super(arg = SomeOtherClass.func())
这句当然不能这样写了
【 在 ValensZC (Cowboy Style in Mind) 的大作中提到: 】
: 最近看书中间有这么一个题
: public class Thing {
: public Thing(int i) { ... }
: ...................
明白了,非常感谢!
【 在 ox 的大作中提到: 】
: 改成这样
: public class MyThing extends Thing {
: private final int arg;
: ...................
这样不可以吧?
如果显示调用父类构造器,那么这个构造器必须在子类构造器的第一行。
【 在 ox 的大作中提到: 】
: 改成这样
: public class MyThing extends Thing {
: private final int arg;
: ...................
而且,父类构造方法必须在子类构造方法之前执行,所以super(arg...)这里,由于要传入子类的变量arg,在执行父类的构造函数之前要先执行子类的构造函数,这是不允许的。
可以使用static修饰arg:
public class MyThing extends Thing {
  private staitc int arg;
  public MyThing() {
   super(arg = SomeOtherClass.func());
   ...
  }
}