一、概念
多态,是允许不同类的对象对同一消息做出不同的响应,是面向对象最核心的特征。
举个栗子,打印机,有黑白的打印机,可以打印黑白效果,有彩色打印机,可以打印彩色效果。
再举个栗子,上课铃响了,上体育课的学生跑到操场上站好,上语文课的学生在教室里坐好一样。
再再举个栗子,动物们都会叫,猫咪叫声是喵喵喵,狗叫声是汪汪汪。
二、分类
1)编译时多态(也叫设计时多态,举例如方法重载)
2)运行时多态(程序运行时决定调用哪个方法)【一般情况下在Java中提到多态指的是运行时多态。】
三、多态存在的三个必要条件
1)要有继承关系
2)子类要重写父类的方法
3)父类引用指向子类对象
四、简单理解
如果不去理解多态的原理,就从使用的角度来讲,可以总结出了多态无非就是三句话:
比如我们有一个父类Father,有一个子类Children
1、向上转型是自动的。即Father f = new Children()是自动的,不需要强转
2、向下转型要强转。即Children c = new Father()是无法编译通过的,必须要Children c = (Children)new Father(),让父类知道它要转成具体哪个子类
3、父类引用指向子类对象,子类重写了父类的方法,调用父类的方法,实际调用的是子类重写了的父类的该方法。即Father f = new Children(),f.toString()实际上调用的是Children中的toString()方法
参考资料:https://www.cnblogs.com/zhilu-doc/p/5338264.html
五、向上转型&向下转型&instanceof运算符
父类Animal
public class Animal { //属性:昵称、年龄 private String name; private int month; //无参构造 public Animal(){ } //带参构造 public Animal(String name, int month){ this.name=name; this.month=month; } //get、set方法 public String getName() { return name; } public void setName(String name) { this.name = name; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } //方法:吃东西 public void eat(){ System.out.println("动物都有吃东西的能力"); }; // 方法:静态方法say public static void say(){//static静态方法,只能被继承,不能被重写 System.out.println("动物间打招呼"); } }