public class This_testing {
int x,y;
public This_testing(int x,int y){ //Why modifier void here would cause exception?
this.x=x;
this.y=y;
}
public static void main(String [] args){
This_testing t =new This_testing(40,50);
System.out.println(t.x+" "+t.y);
}
}
为什么对构造函数 This_testing 使用修饰符 void 会导致以下异常:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code -
constructor This_testing in class practice.This_testing cannot be applied to given types;
required: no arguments
found: int,int
reason: actual and formal argument lists differ in length
at practice.This_testing.main(This_testing.java:13)
最佳答案
构造函数不返回任何内容,甚至 void
也不返回。这就是它们在语言规范中的定义方式。
您可以创建一个名为 This_testing
的方法,该方法返回 void
但这将被视为方法,而不是构造函数(因此,使用 new This_testing( x, y)
无法编译)。
关于java - 导致异常的构造函数的 void 修饰符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20206006/