Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么void方法中不允许使用this()?_Java_Constructor_This - Fatal编程技术网

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

Java 为什么void方法中不允许使用this()?,java,constructor,this,Java,Constructor,This,我正在使用public void A()方法创建一个类,该方法将this()作为第一条语句。一个()方法显然不是一个构造函数,但编译器抱怨这个()不是某个构造函数的第一条语句,我相信它是以super()作为第一条语句隐式创建的。编译器引用的构造函数和this()语句是什么?多谢各位 class A { public void A(){this();} } 输出 错误:对该语句的调用必须是构造函数中的第一个语句 public void A(){this();} ^ 1错误super()引

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

class A
{
    public void A(){this();}
}
输出 错误:对该语句的调用必须是构造函数中的第一个语句 public void A(){this();} ^ 1错误
super()
引用父类的构造函数,而this()引用子类的构造函数。您不能在任何地方使用
this()

          A(int x){
              this(); // Calling a no argument constructor of the same class
          }
但这是无效的,它会抛出编译错误,因为这是递归构造函数调用

          A(){
             this();
          }
不能在方法中使用
this()

super()
表示父类的构造函数,this()表示子类的构造函数。您不能在任何地方使用
this()

          A(int x){
              this(); // Calling a no argument constructor of the same class
          }
但这是无效的,它会抛出编译错误,因为这是递归构造函数调用

          A(){
             this();
          }

不能在方法中使用
this()

因为
this()
只允许作为构造函数中的第一条语句,而
void
函数不是构造函数。您需要
public A(){}
-使用
this()
会有无限递归。感谢您的澄清,因为
this()
只允许作为构造函数中的第一条语句,而
void
函数不是构造函数。您需要
public A(){}
-使用
this()
将有无限递归。感谢您的澄清感谢您的解释。编译器将public void A()方法称为构造函数,这令人困惑。错误消息并没有反映我认为的真正问题。你是对的。这可能被报告为编译器错误:-)非常感谢您的解释。编译器将public void A()方法称为构造函数,这令人困惑。错误消息并没有反映我认为的真正问题。你是对的。可以报告为编译器错误:-)