1.何为多态性?
对象的多态性:父类的引用指向子类的对象(或子类的对象赋给父类的引用)
2.多态的使用:虚拟方法调用
有了对象的多态性以后,我们在编译器,只能调用父类中声明的方法,在运行期实际执行的时候,执行的是子类重写的方法
3.多态性的使用前提:
3.1.要有类的继承关系
3.2.要有方法的重写
class Person{ int age; public void eat(){ System.out.println("eat!"); } } class Man extends Person{ public void eat(){ System.out.println("eat shit"); } public void earnMoney(){ System.out.println("earn!"); } } public class PersonTest{ public static void main(String[] args){ Person p = new Man(); //注意!new 的是 Man ! p.eat(); //p.earnMoney(); //无法调用 } }
原文:https://www.cnblogs.com/DiamondDavid/p/13903565.html