首页 > 解决方案 > 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

怎么了?

标签: java

解决方案


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

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;
}

推荐阅读