- 理解多态性:可以理解为一个事物的多种形态
public class Person { }
public class Man extends Person{ }
Person p1 = new Man();
- 何为多态性:
- 对象的多态性:父类的引用指向子类的对象(或子类的对象赋给父类的引用)
- 多态的使用:当调用子父类同名同参数的方法时,实际执行的是子类重写父类的方法------虚拟方法调用
- 有了对象的多态性以后,我们在编译期,只能调用父类中声明的方法,但在执行期,实际执行的是子类重写的方法
- 多态性的使用前提;
- 类的继承关系
- 方法的重写
否则没有必要使用多态
- 对象的多态性,只适用于方法,不适用于属性
多态是一种运行时行为,而非编译时行为
运行时行为只在代码运行后才可以确定,二编译时行为无需运行,可以直接得到结果
public class Interview {
public static void main(String[] args) {
int key = new Random().nextInt(3);
Animal animal = select(key);
animal.eat();
}
public static Animal select(int key) {
switch(key) {
case 0:
return new Dog();
case 1:
return new Sheep();
default:
return new Cat();
}
}
}
class Animal{
public void eat() {
}
}
class Dog extends Animal{
public void eat() {
System.out.println("Dog eat bone");
}
}
class Cat extends Animal{
public void eat() {
System.out.println("Cat eat fish");
}
}
class Sheep extends Animal{
public void eat() {
System.out.println("Sheep eat grass");
}
}
- 向下转型:使用强制类型转换符
使用强转时,可能出现ClassCastException异常
- instanceof关键字的使用:
- a instanceof A:判断对象a是否为A的实例。如果是,返回true,如果不是,返回false
- 使用情境:为了避免在向下转型时出现ClassCastException异常,在向下转型前,先进行instanceof的判断,如果返回true,再进行向下转型。
如果a instanceof A返回true,则a instanceof B也返回true
其中,B是A的父类