int a(int i)和void a(int i)互为重载对方法吗
时间: 2023-12-22 14:03:43 浏览: 32
是的,`int a(int i)` 和 `void a(int i)` 是互为重载方法。方法的重载是指在同一个类中,方法名相同但参数列表不同的方法。在这种情况下,方法名相同,参数类型相同,但返回类型不同,因此它们是互为重载方法。
以下是一个重载的例子:
```
public class MyClass {
public void myMethod(int num) {
System.out.println("void 参数: " + num);
}
public int myMethod(int num) {
System.out.println("int 参数: " + num);
return num;
}
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.myMethod(10); // 调用 myMethod(void)
int result = obj.myMethod(20); // 调用 myMethod(int)
System.out.println("返回值: " + result);
}
}
```
在上面的例子中,我们定义了两个名字相同但参数类型不同的方法 `myMethod`,一个返回类型为 `void`,另一个返回类型为 `int`。在 `main` 方法中,我们创建了 `MyClass` 的一个对象,并分别调用了 `myMethod(void)` 和 `myMethod(int)` 方法。由于方法名和参数类型相同,编译器可以根据方法调用时传入的参数类型和返回类型来确定要调用哪个方法。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)