多态
同一个对象,在不同时刻表现出来的不同形态
多态的前提
- 有继承/实现关系
- 有重写方法
- 有父类引用子类指向对象
多态访问成员变量的特点
- 成员变量:编译看左边,执行看右边
- 成员方法:编译看左边,执行看右边
成员变量和成员方法访问不一样的原因:
为成员方法有重写,而成员变量没有
public class Animal {
public int age=40;
public void eat(){
System.out.println("动物吃东西");
}
}
public class Cat extends Animal {
public int age=20;
public int weight=10;
@Override
public void eat() {
System.out.println("猫吃鱼");
}
public void playGame(){
System.out.println("猫捉迷藏");
}
}
public class AnimalDemo {
public static void main(String[] args) {
Animal a=new Cat();
System.out.println(a.age);
//System.out.println(a.weight);
a.eat();
//a.playGame();
}
}
多态好处和弊端
- 多态的好处:提高了扩展属性,例如:定义方法的时候,使用父类型作为参数,将来在使用的时候,使用具体的子类型参与操作
- 多态弊端:不能使用子类的特有功能
public class AnimalOperator {
public void userAnimal(Animal a){
a.eat();
}
}
public class Cat extends Animal {
@Override
public void eat() {
System.out.println("猫吃鱼");
}
}
public class Dog extends Animal {
@Override
public void eat() {
System.out.println("狗吃骨头");
}
}
多态中的转型
- 向上转型—>从子到父,父类引用指向子类对象
- 向下转型—>从父到子,父类引用转为子类对象
public class AnimalDemo {
public static void main(String[] args) {
Animal a=new Cat(); //向上转型
a.eat();
Cat c=(Cat)a; //向下转型
c.eat();
c.playGame();
}
}