重载和重写的区别 代码表示
时间: 2023-09-23 17:07:38 浏览: 55
重载 (Overloading) 和重写 (Overriding) 是面向对象编程中常见的两个概念。
重载指的是在同一个类中定义多个同名的方法,但它们的参数类型、个数或顺序不同。编译器会根据调用时传入的参数类型、个数或顺序来自动匹配调用对应的方法。如下面的代码所示:
```
public class OverloadingExample {
public void print(int num) {
System.out.println("Printing int: " + num);
}
public void print(String str) {
System.out.println("Printing string: " + str);
}
public void print(double num) {
System.out.println("Printing double: " + num);
}
}
public static void main(String[] args) {
OverloadingExample example = new OverloadingExample();
example.print(10);
example.print("Hello, world!");
example.print(3.14159);
}
```
在这个例子中,`OverloadingExample` 类中定义了三个名为 `print` 的方法,它们分别接受一个整数、一个字符串和一个双精度浮点数作为参数。在 `main` 方法中,我们创建了一个 `OverloadingExample` 的实例,并分别调用了三个不同的 `print` 方法。由于它们的参数类型不同,编译器会自动匹配调用对应的方法。
重写指的是子类重写父类的方法,使得子类可以根据自己的需要重新实现该方法。重写的方法必须与父类的方法具有相同的方法名、参数列表和返回类型。如下面的代码所示:
```
public class Animal {
public void sound() {
System.out.println("The animal makes a sound");
}
}
public class Dog extends Animal {
@Override
public void sound() {
System.out.println("The dog barks");
}
}
public static void main(String[] args) {
Animal animal = new Animal();
animal.sound(); // 输出:The animal makes a sound
Dog dog = new Dog();
dog.sound(); // 输出:The dog barks
}
```
在这个例子中,`Animal` 类中定义了一个名为 `sound` 的方法。`Dog` 类继承 `Animal` 类,并重写了 `sound` 方法。在 `main` 方法中,我们创建了一个 `Animal` 的实例和一个 `Dog` 的实例,并分别调用了它们的 `sound` 方法。由于 `Dog` 类重写了 `sound` 方法,所以当我们调用 `dog.sound()` 时输出的是 "The dog barks" 而不是 "The animal makes a sound"。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)