多态含义
- 事物存在的多种形态
多态前提
- 要有继承关系
- 要有⽅法重写
- 要有⽗类引⽤⼦类对象
案例
public class Demo1_Polymorphic {
public static void main(String[] args){
Cat c = new Cat();
c.eat();
Animal a = new Cat(); //⽗类引⽤指向⼦类对象
a.eat();
}
}
class Animal{
public void eat(){
System.out.println("Animal eat food");
}
}
class Cat extends Animal{
public void eat(){
System.out.println("Cat eat fish");
}
}
//控制台
Cat eat fish
Cat eat fish
案例2
public class Demo2_Polymorphic {
public static void main(String[] args)
{
Father f = new Son();
System.out.println(f.num);
//10
Son s = new Son();
System.out.println(s.num);
//20
}
}
class Father{
int num = 10;
}
class Son extends Father{
int num = 20;
}
好处——可以接受任意⼦类对象
- 提⾼了代码的维护性(继承保证)
- 提⾼了代码的扩展性(多态保证)
弊端
- 不能使⽤⼦类的特有属性和⾏为