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

标签 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

即使很难,我在使用“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/

相关文章:

Android 字符串数组语言环境验证

android - 不能将 GLSurfaceView 放在 SurfaceView 上吗?

javascript - 使用javascript捕获在android虚拟键盘上键入的键

java - 有什么办法可以为ant项目做一个launchpad ppa吗?

java - 系统计时的最佳度量单位是什么

java - 如何在内存中保存完整的Solr索引?

java - 从 m 个集合中获取 n 个元素的所有不同组合

java - 在不同的项目中重用 Java 包

android - 将 iPhone 应用程序移植到 Android?如何说服他们不要

android - 是否有更好(即更快)的 Android 模拟器用于调试?