java - 为什么 void 方法中不允许使用 this() ?

标签 java constructor this

我正在使用 public void A() 方法创建类 A,该方法将 this() 作为第一个语句。 A() 方法显然不是构造函数,但编译器提示 this() 不是某个构造函数的第一个语句,我相信它是用 super() 作为第一个语句隐式创建的。编译器引用什么构造函数和 this() 语句?谢谢。

class A
{
    public void A(){this();}
}

输出 错误:对此的调用必须是构造函数中的第一个语句 公共(public)无效A(){这个();} ^ 1 个错误

最佳答案

super()指的是父类的构造函数,this()指的是子类的构造函数。除了在具有不同签名的构造函数中并且仅作为第一条语句之外,您不能在任何地方使用 this()。例如,this 是有效的。

          A(int x){
              this(); // Calling a no argument constructor of the same class
          }

但是这是无效的,它会抛出编译错误,因为这是递归构造函数调用。

          A(){
             this();
          }

您不能在方法中使用 this()

关于java - 为什么 void 方法中不允许使用 this() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50653682/

相关文章:

java - 使用 Spring AOP 触发了哪个接口(interface)(扩展 CrudRepository)的删除方法?

c++ - OpenGL C++ : Struct wrapper for VBO won't initialize members

c++ - 析构函数删除函数中的拷贝返回动态结构

java - 是否有有效的工具将.Net C# webservice 转换为java webservice?

java - 使用 hashcode() 对数组长度取模返回空指针异常

javascript - 正则表达式构造函数和文字之间的反斜杠差异

properties - Kotlin:返回 "this"的默认 setter

javascript - JS 对象 this.method() 通过 jQuery 中断

reactjs - 在 React 中对类属性使用箭头函数。不清楚

java - Joda DateTimeFormatter 设置时区时抛出异常 : "is malformed at"