【问题标题】:void modifier for constructor causing exception构造函数的 void 修饰符导致异常
【发布时间】:2013-11-25 23:59:53
【问题描述】:
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)

【问题讨论】:

  • 与您的问题无关,但x=x; 行没有任何作用。
  • @DavidWallace:谢谢

标签: java constructor modifier


【解决方案1】:

构造函数不返回任何内容,甚至 void。这只是它们在语言规范中的定义方式。

您可以创建一个名为This_testing 的方法,该方法返回void,但这将被视为方法,而不是构造函数(因此,使用new This_testing(x, y) 不会编译)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 2012-11-12
    相关资源
    最近更新 更多