用Java写一个程序,使用两种方法体现类的多态性
时间: 2023-12-03 09:02:06 浏览: 40
好的,我们来写一个简单的程序,演示Java中类的多态性。
首先,定义一个父类Animal,其中包含一个方法`makeSound()`:
```java
public class Animal {
public void makeSound() {
System.out.println("Animal makes sound.");
}
}
```
然后,定义两个子类Dog和Cat,它们继承自Animal,并重写了`makeSound()`方法:
```java
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Dog barks.");
}
}
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Cat meows.");
}
}
```
接下来,我们可以定义一个方法`animalMakesSound()`,该方法接收一个Animal类型的参数,并调用它的`makeSound()`方法:
```java
public class Main {
public static void animalMakesSound(Animal animal) {
animal.makeSound();
}
public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();
animalMakesSound(animal1);
animalMakesSound(animal2);
}
}
```
在`main`方法中,我们分别定义了一个Dog对象和一个Cat对象,并将它们赋值给Animal类型的变量。然后,我们调用了`animalMakesSound()`方法,分别传入这两个Animal类型的参数。由于Dog和Cat都是Animal的子类,并且它们都重写了`makeSound()`方法,所以当我们调用`animal.makeSound()`方法时,实际上调用的是Dog或Cat中的`makeSound()`方法,这就是Java中的多态性。
除了方法参数的多态性,我们还可以使用类型转换实现类的多态性。例如,我们可以将一个Animal类型的变量强制转换为Dog类型或Cat类型:
```java
Animal animal = new Dog();
Dog dog = (Dog) animal;
dog.makeSound();
```
在这个例子中,我们将一个Animal类型的变量强制转换为Dog类型,并调用了它的`makeSound()`方法。由于我们在定义Dog类时重写了`makeSound()`方法,所以这里实际上调用的是Dog类中的`makeSound()`方法。
这两种方法都体现了Java中的多态性,即一个对象可以被看作是它所属的类的类型,也可以被看作是它所继承的父类或实现的接口的类型。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.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)