何为多态性?其实可以理解为一个事物的多种形态,父类引用子类的对象或子类的对象赋给父类的引用。
目录
多态性使用前提
1. 类的继承关系
2. 方法的重写
虚拟方法调用
有了对象的多态性以后,我们在编译期,只能调用父类中声明的方法,但是在运行期,我们实际执行的是子类重写父类的方法
总结:编译看左;运行看右
注:多态性只适用于方法,不适用于属性(编译运行都看左边)
多态是一种运行时行为
代码案例
import java.util.Random;
class Animal{
public void eat() {
System.out.println("animal eat food");
}
}
class Cat extends Animal{
public void eat() {
System.out.println("cat eat fish");
}
}
class Dog extends Animal{
public void eat() {
System.out.println("dog eat bone");
}
}
class Lion extends Animal{
public void eat() {
System.out.println("lion eat meat");
}
}
public class AnimalTest {
public static Animal getInstance(int key) {
switch(key) {
case 0:
return new Cat();
case 1:
return new Dog();
default:
return new Lion();
}
}
public static void main(String[] args) {
int key = new Random().nextInt(3); // 取0,1,2随机数
System.out.println(key);
Animal animal = getInstance(key); // 多态性的使用,父类的引用指向子类的对象
animal.eat(); // 虚拟方法调用
}
}