编写程序,实现重写和重载的效果
时间: 2024-05-15 19:16:41 浏览: 10
重写和重载是面向对象程序设计中的两个重要概念。下面是一个实现重写和重载的示例程序:
```java
public class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
public void makeSound(String sound) {
System.out.println("The animal makes a " + sound + " sound");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("The dog barks");
}
public void makeSound(String sound) {
System.out.println("The dog barks " + sound);
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
animal.makeSound(); // The animal makes a sound
animal.makeSound("loud"); // The animal makes a loud sound
Dog dog = new Dog();
dog.makeSound(); // The dog barks
dog.makeSound("loudly"); // The dog barks loudly
Animal dog2 = new Dog();
dog2.makeSound(); // The dog barks
dog2.makeSound("softly"); // The animal makes a softly sound
}
}
```
在上面的示例中,Animal类有两个相同名称但参数不同的makeSound方法。这就是重载。Dog类重写了Animal类的makeSound方法,这就是重写。在Main类中,我们创建了Animal和Dog对象,并调用它们的makeSound方法。我们还创建了一个Animal类型的Dog对象,这个对象实际上是一个Dog对象,但是由于声明为Animal类型,所以只能调用Animal类的方法。当我们调用dog2的makeSound方法时,它实际上调用了Dog类的makeSound方法,这就是多态性的体现。
相关推荐
![](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)