目录
🧾多态的概念:通俗来说,就是多种形态,具体点就是去完成某个行为,当不同的对象去完成时会产生出不同的状态。

➡️总的来说:同一件事情,发生在不同对象身上,就会产生不同的结果。
✨在java中要实现多态,必须要满足如下几个条件,缺一不可:
1. 必须在 继承体系下2. 重写3. 向上转型:实际就是创建一个子类对象,将其当成父类对象来使用。
🌈多态体现:在代码运行时,当传递不同类对象时,会调用对应类中的方法。
- class Animal {
- public String name;//成员属性
- public int age;
-
- public void eat() {
- System.out.println(name+" 吃饭");
- }
- }
- class Dog extends Animal {
- public void wangwang() {
- System.out.println(name+" 正在汪汪叫");
- }
- }
- class Bird extends Animal {
- public String wing;//翅膀
-
- public void fly() {
- System.out.println(name + " 正在飞");
- }
- }
- public class Test2 {
- Dog dog = new Dog();
- dog.name = "十三月";
- dog.eat();
- dog.wangwang();
- //理论上:等号两边的数据类型必须一致,否则赋值会会出错
- Animal animal1 = dog;//这里可以赋值是因为父子类关系
-
- Bird bird = new Bird();
- bird.name = "圆圆";
- bird.eat();
- bird.fly();
- Animal animal2 = bird;
-
- }
- }
-
- 运行结果:
- 十三月 吃饭
- 十三月 正在汪汪叫
- 圆圆 吃饭
- 圆圆 正在飞
✨向上转型:实际就是创建一个子类对象,将其当成父类对象来使用。
➡️语法格式:父类类型 对象名 = new 子类类型()
Animal animal1 = new Dog();
【使用场景】
1️⃣直接赋值:子类对象赋值给父类对象
- public static void main(String[] args) {
- //向上转型
- Animal animal1 = new Dog();
- animal1.name = "十三月";
- animal1.eat();
-
- //发生向上转型,通过父类的引用,只能访问父类特有的成员,不能访问到子类特有的成员
- //animal1.wangwang();//error
-
- System.out.println("=============");
- //向上转型
- Animal animal2 = new Bird();
- animal2.name = "圆圆";
- animal2.eat();
- }
❗❗❗发生向上转型,通过父类的引用,只能访问父类特有的成员,不能访问到子类特有的成员
2️⃣方法传参:形参为父类型引用,可以接收任意子类的对象
- //通过方法的传参
- public static void func(Animal animal) {
-
- }
- public static void main(String[] args) {
- Dog dog = new Dog();
- func(dog);
- }
3️⃣方法返回:返回任意子类对象
- //方法返回
- public static Animal func2() {
- return new Dog();
- }
✅向上转型的优点:让代码实现更简单灵活。
❎向上转型的缺陷:不能调用到子类特有的方法。
📖重写(override):也称为覆盖。重写是子类对父类非静态、非private修饰,非final修饰,非构造方法等的实现过程进行重新编写, 返回值和形参都不能改变。即外壳不变,核心重写!重写的好处在于子类可以根据需要,定义特定于自己的行为。 也就是说子类能够根据需要实现父类的方法。
重写的条件:
1️⃣方法名称相同
2️⃣参数列表相同
3️⃣返回值相同
- class Animal {
- public String name;//成员属性
- public int age;
-
- public void eat() {
- System.out.println(name+" 吃饭");
- }
- }
- class Dog extends Animal {
- public void wangwang() {
- System.out.println(name + " 正在汪汪叫");
- }
- @Override//注解:这个注解的意思就是,当前这个方法是被重写的
- public void eat() {
- System.out.println(name + "正在吃狗粮");
- }
- }
- class Bird extends Animal {
- public String wing;//翅膀
-
- public void fly() {
- System.out.println(name + " 正在飞");
- }
-
- @Override
- public void eat() {
- System.out.println(name + "正在吃鸟粮");
- }
- }

🔺【方法重写的规则】
1️⃣子类在重写父类的方法时,一般必须与父类方法原型一致: 返回值类型 方法名 (参数列表) 要完全一致
2️⃣被重写的方法返回值类型可以不同,但是必须是具有父子关系的
3️⃣访问权限不能比父类中被重写的方法的访问权限更低。(private < 默认 < protected < public)例如:如果父类方法被public修饰,则子类中重写该方法就不能声明为 protected
4️⃣父类被static、private修饰的方法、构造方法都不能被重写。
5️⃣重写的方法, 可以使用 @Override 注解来显式指定. 有了这个注解能帮我们进行一些合法性校验. 例如不小心 将方法名字拼写错了 (比如写成 aet), 那么此时编译器就会发现父类中没有 aet 方法, 就会编译报错, 提示无法构成重写.
6️⃣被 final 修饰的方法是不能被重写的,此时这个方法被称做密封方法
- @Override//注解:这个注解的意思就是,当前这个方法是被重写的
- public void eat() {
- System.out.println(name + "正在吃狗粮");
- }
【重写和重载的区别】


🔺【重写的设计原则】
✨对于已经投入使用的类,尽量不要进行修改。最好的方式是:重新定义一个新的类,来重复利用其中共性的内容,并且添加或者改动新的内容。
➡️动态绑定:也称为后期绑定(晚绑定),即在编译时,不能确定方法的行为,需要等到程序运行时,才能够确定具体调用那个类的方法。
- public static void main(String[] args) {
- //向上转型
- Animal animal1 = new Dog();//直接赋值
- animal1.name = "十三月";
- animal1.eat();
-
- //发生向上转型,通过父类的引用,只能访问父类特有的成员,不能访问到子类特有的成员
- //animal1.wangwang();//error
-
- System.out.println("=============");
- //向上转型
- Animal animal2 = new Bird();//直接赋值
- animal2.name = "圆圆";
- animal2.eat();
- }
上述代码不应该调用父类里的eat();,在这里为什么调用子类的eat();?
✅在这里发生了动态绑定(编译的时候调用了animal eat(),但是在运行的时候被绑到了子类的eat()上)
动态绑定前提:1️⃣向上转型;2️⃣重写;3️⃣通过父类引用,调用这个父类和子类重写的方法

➡️静态绑定:也称为前期绑定(早绑定),即在编译时,根据用户所传递实参类型就确定了具体调用那个方法。典型代表函数重载
- public static int add(int a,int b) {
- return a + b;
- }
- public static int add(int a, int b, int c) {
- return a + b + c;
- }
-
- public static void main(String[] args) {
- System.out.println(add(1,2));//静态绑定
- System.out.println(add(1,2,3));
- }
- class Animal {
- public String name;//成员属性
- public int age;
-
- public void eat() {
- System.out.println(name+" 吃饭");
- }
- }
- class Dog extends Animal {
- @Override//注解:这个注解的意思就是,当前这个方法是被重写的
- public void eat() {//重写:1️⃣方法名称相同2️⃣参数列表相同3️⃣返回值相同
- System.out.println(name + "正在吃狗粮");
- }
- }
- class Bird extends Animal {
- @Override
- public void eat() {//重写
- System.out.println(name + "正在吃鸟粮");
- }
- }
- public class Test2 {
- public static void function(Animal animal) {
- animal.eat();
- }
- public static void main(String[] args) {
- Animal animal1 = new Dog();//直接赋值
- animal1.name = "十三月";
- function(animal1);
-
- System.out.println("=============");
- //向上转型
- Animal animal2 = new Bird();//直接赋值
- animal2.name = "圆圆";
- function(animal2);
- }
- }

👆多态:当父类引用,引用的对象不一样的时候,表现出来的行为是不一样的!!!
➡️将一个子类对象经过向上转型之后当成父类方法使用,再无法调用子类的方法,但有时候可能需要调用子类特有的方法,此时:将父类引用再还原为子类对象即可,即向下转换。

- class Animal {
- public String name;//成员属性
- public int age;
- }
- class Dog extends Animal {
- public void wangwang() {
- System.out.println(name + " 正在汪汪叫");
- }
- }
- public class Test2 {
- public static void main(String[] args) {
- Animal animal1 = new Dog();
- //向下转型
- Dog dog = (Dog) animal1;
- dog.name = "haha";
- dog.wangwang();
- }
- }
➡️向下转型用的比较少,而且不安全,万一转换失败,运行时就会抛异常。Java中为了提高向下转型的安全性,引入了 instanceof ,如果该表达式为true,则可以安全转换。
- public class Test2 {
- public static void main(String[] args) {
- Animal animal1 = new Dog();
- //向下转型
- //Dog dog = (Dog) animal1;
- //dog.name = "haha";
- //dog.wangwang();
-
- 可以理解为:animal这个引用 是不是引用了Bird对象
- if(animal1 instanceof Bird) {
- Bird bird = (Bird) animal1;
- bird.fly();
- }
- }
- }
✅instanceof 关键词官方介绍:https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.20.2
➡️假设有如下代码:
- class Shape {
- public void draw() {
- System.out.println("画图形!");
- }
- }
- class Rect extends Shape {
- @Override
- public void draw() {
- System.out.println("画矩形!");
- }
- }
- class Cycle extends Shape {
- @Override
- public void draw() {
- System.out.println("画圆!");
- }
- }
- class Flower extends Shape {
- @Override
- public void draw() {
- System.out.println("❀!");
- }
- }
- public class Test3 {
- public static void drawMap(Shape shape) {
- shape.draw();
- }
- public static void main(String[] args) {
- Rect rect = new Rect();
- Cycle cycle = new Cycle();
-
- drawMap(rect);
- drawMap(cycle);
- drawMap(new Flower());
- }
- }
- //输出结果:
- //画矩形!
- //画圆!
- //❀!
➡️【使用多态的好处】
1️⃣能够降低代码的 "圈复杂度", 避免使用大量的 if -else
什么叫 "圈复杂度" ?圈复杂度是一种描述一段代码复杂程度的方式. 一段代码如果平铺直叙, 那么就比较简单容易理解. 而如果有很多的条件分支或者循环语句, 就认为理解起来更复杂.因此我们可以简单粗暴的计算一段代码中条件语句和循环语句出现的个数, 这个个数就称为 "圈复杂度".如果一个方法的圈复杂度太高, 就需要考虑重构.不同公司对于代码的圈复杂度的规范不一样. 一般不会超过 10
✨例如我们现在需要打印的不是一个形状了, 而是多个形状. 如果不基于多态, 实现代码如下:
- class Shape {
- public void draw() {
- System.out.println("画图形!");
- }
- }
- class Rect extends Shape {
- @Override
- public void draw() {
- System.out.println("画矩形!");
- }
- }
- class Cycle extends Shape {
- @Override
- public void draw() {
- System.out.println("画圆!");
- }
- }
- class Flower extends Shape {
- @Override
- public void draw() {
- System.out.println("❀!");
- }
- }
- public class Test3 {
- public static void drawMap2() {
- Rect rect = new Rect();
- Cycle cycle = new Cycle();
- Flower flower = new Flower();
- //cycle rect cycle rect flower
- String[] shapes = {"cycle", "rect", "cycle", "rect", "flower"};
- for (String s :shapes) {
- if(s.equals("cycle")) {
- cycle.draw();
- }else if(s.equals("rect")) {
- rect.draw();
- }else {
- flower.draw();
- }
- }
- }
-
- public static void main(String[] args) {
- drawMap2();
- }
- }
- //画圆!
- //画矩形!
- //画圆!
- //画矩形!
- //❀!
🔺如果使用使用多态, 则不必写这么多的 if - else 分支语句, 代码更简单.
- public static void drawMap() {
- Rect rect = new Rect();
- Cycle cycle = new Cycle();
- Flower flower = new Flower();
-
- //向上转型
- Shape[] shapes = {cycle,rect,cycle,rect,flower};//里边的每个类型就是Shape类型
-
- for (Shape shape : shapes) {
- drawMap();
- }
- }
- public static void main(String[] args) {
- drawMap3();
- }
- //画圆!
- //画矩形!
- //画圆!
- //画矩形!
- //❀!
2️⃣可扩展能力更强
如果要新增一种新的形状, 使用多态的方式代码改动成本也比较低
- class Triangle extends Shape {
- @Override
- public void draw() {
- System.out.println("△");
- }
- }
➡️对于类的调用者来说(drawShapes方法), 只要创建一个新类的实例就可以了, 改动成本很低.
➡️而对于不用多态的情况, 就要把 drawShapes 中的 if - else 进行一定的修改, 改动成本更高
❎多态缺陷:代码的运行效率降低。
1. 属性没有多态性当父类和子类都有同名属性的时候,通过父类引用,只能引用父类自己的成员属性2. 构造方法没有多态性
- class B {
- public B() {
- // do nothing
- func();
- }
- public void func() {
- System.out.println("B.func()");
- }
- }
- class D extends B {
- private int num = 1;
- @Override
- public void func() {
- System.out.println("11111111111111111");
- }
- }
- public class Test4 {
- public static void main(String[] args) {
- D d = new D();
- }
- }
🌈在这里主函数调用D不带参数的方法,就会默认有一个以下的构造方法:
- class D extends B {
- public D() {
- super();
- }
- }

👉 这时候会执行父类的构造方法,调用func();,那么问题来了,是调用父类的func(),还是子类的func()?

注意:
当在父类的构造方法里边,去调用父类和子类重写的方法的时候,此时会调用子类的!!!
- class B {
- public B() {
- // do nothing
- func();
- }
- public void func() {
- System.out.println("B.func()");
- }
- }
- class D extends B {
- private int num = 1;
- public D() {
- super();
- }
- @Override
- public void func() {
- System.out.println("D.func() " + num);
- }
- }
- public class Test4 {
- public static void main(String[] args) {
- D d = new D();
- }
- }
此时的 num值等于0——因为此时的父类还没有走完
构造 D 对象的同时, 会调用 B 的构造方法.B 的构造方法中调用了 func 方法, 此时会触发动态绑定, 会调用到 D 中的 func此时 D 对象自身还没有构造, 此时 num 处在未初始化的状态, 值为 0. 如果具备多态性,num的值应该是1.所以在构造函数内,尽量避免使用实例方法,除了fifinal和private方法。
💯结论: "用尽量简单的方式使对象进入可工作状态", 尽量不要在构造器中调用方法(如果这个方法被子类重写, 就会触发动态绑定, 但是此时子类对象还没构造完成), 可能会出现一些隐藏的但是又极难发现的问题