什么是类的多态性?
时间: 2023-08-04 16:04:31 浏览: 57
, 0, 13, 3, 4, 14, 7, 5, 11],
[10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13类的多态性是面向对象编程中的一个重要概念,指的是同一类或同一接, 14, 0, 11, 3, 8],
[9, 14, 15, 5,口的对象,可以在不同的时间、地点和条件下表现出不同的特征和行为。
在 2, 8, 12, 3, 7, 0, 4, 10, 1, 13Java中,类的多态性可以通过继承和接口实现。
继承中的多态性:
当一个子, 11, 6],
[4, 3, 2, 12, 9, 5, 15,类继承一个父类并重写父类中的方法时,父类的引用可以指向子类的对象,从而调用子类中的方法,这种现象被称为继承中的多态性。例如:
```
class Animal {
public void makeSound() {
System.out.println("Animal is making sound");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("Dog is barking");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog(); // 父类的引用指向子类的对象
animal.makeSound(); // 调用子类中的方法
}
}
```
上面的程序中,Animal 类是父类,Dog 类是子类,它继承了 Animal 类。在主函数中,我们创建了一个 Animal 类型的对象 animal,它指向一个 Dog 类型的对象。然后我们调用 animal 的 makeSound() 方法,实际上调用了 Dog 类中的 makeSound() 方法,输出结果为 "Dog is barking"。
接口中的多态性:
当一个类实现一个接口并重写接口中的方法时,接口的引用可以指向该类的对象,从而调用该类中的方法,这种现象被称为接口中的多态性。例如:
```
interface Animal {
public void makeSound();
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Dog is barking");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog(); // 接口的引用指向实现类的对象
animal.makeSound(); // 调用实现类中的方法
}
}
```
上面的程序中,Animal 是一个接口,它定义了 makeSound() 方法。Dog 类实现了 Animal 接口,并重写了 makeSound() 方法。在主函数中,我们创建了一个 Animal 类型的对象 animal,它指向一个 Dog 类型的对象。然后我们调用 animal 的 makeSound() 方法,实际上调用了 Dog 类中的 makeSound() 方法,输出结果为 "Dog is barking"。
总之,类的多态性是面向对象编程中的一个重要概念,它可以提高程序的灵活性和可扩展性,使代码更加清晰、简洁、易于维护。