java - 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
怎么了?
解决方案
方法必须定义返回类型,例如
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;
}
推荐阅读
- javascript - 带有 sinon 的 vue 模拟类用于单元测试
- python - 如何忽略 python 中的位置参数并回退到默认值?
- c++ - 继承与纯虚函数混淆,有什么办法不必重新定义它们?
- typescript - 打字稿中的通用 zip,使用 variadc 元组
- ruby - Ruby AWS Lambda - 返回二进制内容时来自 Application Load Balancer 的 502 Bad Gateway
- django - Django drf-social-oauth2 社交注册后备登录
- websocket - 实时音频流网络应用程序的架构
- python-3.x - 如何使用 Google Ads API 批量删除广告?
- r - 如何在 Ggplot 的一张图表上有两条线
- ios - iOS中的Firebase“管理员用户”?