int a(int i)和void a(double i)互为重载对方法吗
时间: 2024-03-08 22:48:17 浏览: 30
不是互为重载方法。方法的重载是指在同一个类中,方法名相同但参数列表不同的方法。
在这种情况下,`int a(int i)` 和 `void a(double i)` 的方法名相同,但参数类型不同,因此它们不互为重载方法。
以下是一个重载的例子:
```
public class MyClass {
public void myMethod(int num) {
System.out.println("int 参数: " + num);
}
public void myMethod(double num) {
System.out.println("double 参数: " + num);
}
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.myMethod(10); // 调用 myMethod(int)
obj.myMethod(10.0); // 调用 myMethod(double)
}
}
```
在上面的例子中,我们定义了两个名字相同但参数类型不同的方法 `myMethod`。在 `main` 方法中,我们创建了 `MyClass` 的一个对象,并分别调用了 `myMethod(int)` 和 `myMethod(double)` 方法。由于参数类型不同,因此编译器可以根据方法调用时传入的参数类型来确定要调用哪个方法。
相关问题
int a(int i)和void a(int i)互为重载对方法吗
是的,`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)` 方法。由于方法名和参数类型相同,编译器可以根据方法调用时传入的参数类型和返回类型来确定要调用哪个方法。
void show(inta,int b)与void show(int x,int y)构成方法重载吗
是的,`void show(int a, int b)` 和 `void show(int x, int y)` 构成方法重载。方法重载指的是在同一个类中定义多个具有相同名称但参数列表不同的方法。在这种情况下,方法名称相同,但参数列表中的参数名称和类型不同。
在你提供的例子中,`show` 方法的名称相同,但参数列表中的参数名称和类型不同:一个方法有 `int a` 和 `int b` 作为参数,另一个方法有 `int x` 和 `int y` 作为参数。这符合方法重载的定义。
通过方法重载,你可以根据不同的参数类型和个数来调用不同的方法,提高代码的灵活性和复用性。在使用时,编译器会根据调用时提供的参数类型和个数来确定具体调用哪个重载方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)