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
怎么了?
答案 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;
}