java - 导致异常的构造函数的 void 修饰符

标签 java constructor modifier

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/

相关文章:

swiftui - 如何对不同的形状使用相同的修饰符集

python - 如何使用另一个 numpy 数组修改 pandas 数据框中的所有值

java - 接口(interface)中的 protected 方法

java - 如何在java中注册mysql游标?

java - hashmap 在下面的场景中表现如何?

java - Scala 中构造函数的通用参数

c++ - 为用户定义的类正确调用复制构造函数/赋值运算符

java - Java构造函数中的最终参数

java - 将 war 部署到 JBoss AS 7 时出错(域模式): "Failed to process phase STRUCTURE of deployment"

java - 如何在不使用 EOMONTH 的情况下在 Excel 中查找上个月的最后一天