java如何将此传递给另一个构造函数(构造函数重载)?

时间:2015-04-02 07:52:00

标签: java android

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

即使很难我在使用之前调用super(c)"这个",有没有办法克服这个错误?

2 个答案:

答案 0 :(得分:2)

你不能对构造函数进行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这个,并在扩展构造函数中处理它。

答案 1 :(得分:0)

查看工作流程:

CustomView(c,animate) ---> CustomView(c) ---> CustomView(c,animate, bind) ---> CustomView(c)

当您执行this(c,animate, this)然后在super(c)中致电CustomView(c,animate, bind)时,

Cannot reference "this" before supertype constructor has been called发生。

相反,如果你这样做了

CustomView(Context c, Boolean animate) {
    this(c, animate, this);
}

CustomView(Context c, Boolean animate, CustomView bind) {
    super(c);

    //other actions

}