CustomView(Context c, Boolean animate) {
super(c);
this(c, animate, this);
}
CustomView(Context c, Boolean animate, CustomView bind) {
super(c);
//other actions
}
我想将其传递给另一个参数比这更多的构造函数,但我收到一个错误:
Cannot reference "this" before supertype constructor has been called
即使很难,我在使用“this”之前调用 super(c),有办法克服这个错误吗?
最佳答案
不能对构造函数进行 3 次调用。您需要选择其中之一
CustomView(Context c, Boolean animate) {
super(c); //fisrt call
this(c, animate, this); //second call
}
CustomView(Context c, Boolean animate, CustomView bind) {
super(c); //third call
//other actions
}
你应该做类似的事情
CustomView(Context c, Boolean animate) {
this(c, animate, null);
}
CustomView(Context c, Boolean animate, CustomView bind) {
super(c); //third call
if(bind==null) {bind=this}
//do whatever you like with your "bindings"
}
编辑:
我发现,OP其实也有一些麻烦。例如。此代码无法编译!:
class Foo{
Foo(Object o){
}
}
class FooBar extends Foo {
FooBar(Object o, Boolean a){
this(o,a,this);
}
FooBar(Object o, Boolean a, FooBar fb){
super(o);
}
}
this(o,a,this);
行出错如下
Cannot refer to 'this' nor 'super' while explicitly invoking a constructor
所以他的逻辑解决方案是传递 null
而不是这个,并在扩展构造函数中处理它。
关于java 如何将其传递给另一个构造函数(构造函数重载)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29407728/