Java程序错误中的方法重载

时间:2018-08-16 12:22:54

标签: java

class Test {
    int x, y;

    calc(int a) {
        x = a;
        System.out.println("Square is " + (x * x));
    }

    calc(int a, int b) {
        x = a;
        y = b;
        System.out.println("Addition is " + (x + y));
    }
}

class Main {
    public static void main(String[] args) {
        Test obj = new Test();
        obj.calc(10, 20);
        obj.calc(10);
    }
}
methodOverloading.java:3: error: invalid method declaration; return type required
    calc(int a){
    ^
methodOverloading.java:7: error: invalid method declaration; return type required
    calc(int a,int b){
    ^
2 errors

怎么了?

1 个答案:

答案 0 :(得分:3)

方法必须定义一个返回类型,例如

public static void main(String[] args)

void声明为返回类型(即“不返回任何内容,只需在方法中执行某些操作”)。

由于您的方法似乎可以计算乘法和加法,但不返回任何内容,因此应为它们指定相应的返回类型:

void calc(int a)

void calc(int a, int b)

如果您希望该方法不打印结果而是返回结果,则必须调整返回类型并在方法主体中添加return语句,如下所示:

int calc(int a) {
    // returns the square of a, which is again an integer
    return a * a;
}