【JavaSE】-- 多态

发布于:2024-10-12 ⋅ 阅读:(124) ⋅ 点赞:(0)

1. 多态的概念

多态的概念:通俗来说,就是多种形态,**具体点就是去完成某个行为,当不同的对象去完成时会产生出不同 的状态(同一间事情,发生在不同对象身上,就会产生不同的结果。**但是这样还是描述的很抽象。

2. 多态实现条件

在java中要实现多态,必须要满足如下几个条件,缺一不可:

  1. 必须在继承体系下
  2. 子类必须要对父类中方法进行重写
  3. 通过父类的引用调用重写的方法

多态体现:在代码运行时,当传递不同类对象时,会调用对应类中的方法。

Animal类:

public class Animal {
    public String name;
    public int age;
    
    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public void eat(){
        System.out.println(this.name + "正在吃饭...");
    }
}

Dog类:

public class Dog extends Animal {

    public Dog(String name, int age) {
        super(name, age);
    }

    @Override
    public void eat() {
        System.out.println(this.name + "正在吃狗粮.....");
    }

    public void bark(){
        System.out.println(this.name + "正在汪汪叫......");
    }
}

Bird类:

public class Bird extends Animal{
    public Bird(String name, int age) {
        super(name, age);
    }

    @Override
    public void eat() {
        System.out.println(this.name + "正在吃鸟粮.....");
    }
}

Test类:

public class Test {
// 编译器在编译代码时,并不知道要调用Dog 还是 Bird 中eat的方法
// 等程序运行起来后,形参animal引用的具体对象确定后,才知道调用那个方法
// 注意:此处的形参类型必须时父类类型才可以
    public static void func(Animal animal){
        animal.eat();
    }
    public static void main(String[] args) {
        Dog dog = new Dog("辣条", 1);
        Bird bird = new Bird("小奔", 2);
        func(dog);
        func(bird);
    }
}
输出结果:
        辣条正在吃狗粮.....
		小奔正在吃鸟粮.......

当类的调用者在编写 eat 这个方法的时候, 参数类型为 Animal (父类), 此时在该方法内部并不知道, 也不关注当前的animal 引用指向的是哪个类型(哪个子类)的实例. 此时 animal 这个引用调用 eat方法可能会有多种不同的表现(和 animal 引用的实例相关), 这种行为就称为 多态.

3. 重写

重写(override):也称为覆盖。重写是子类对父类非静态、非private修饰,非final修饰,非构造方法等的实现过程进行重新编写, 返回值和形参都不能改变。即外壳不变,核心重写!重写的好处在于子类可以根据需要,定义特定于自己的行为。 也就是说子类能够根据需要实现父类的方法。当父类引用 引用了子类对象后,当子类重写了父类的方法之后,通过父类的引用 调用 父类和子类 重写的方法,最终结果显示的是 调用了子类的方法此错咸亨 叫做动态绑定。

【方法重写的规则】

  • 子类在重写父类的方法时,一般必须与父类方法原型一致: 返回值类型 方法名 (参数列表) 要完全一致.
  • 被重写的方法返回值类型可以不同,但是必须是具有父子关系的.
  • 访问权限不能比父类中被重写的方法的访问权限更低。例如:如果父类方法被public修饰,则子类中重写该方法就不能声明为 protected
  • 父类被static、private修饰的方法、构造方法都不能被重写。
  • 重写的方法, 可以使用 @Override 注解来显式指定. 有了这个注解能帮我们进行一些合法性校验. 例如不小心将方法名字拼写错了 (比如写成 aet), 那么此时编译器就会发现父类中没有 aet 方法, 就会编译报错, 提示无法构成重写.

重载和重写的区别:

在这里插入图片描述
重写中的父类的访问修饰限定符的权限一定大于等于子类的访问修饰限定符的权限。

方法重载是一个类的多态性表现,而方法重写是子类与父类的一种多态性表现。


【重写的设计原则】
对于已经投入使用的类,尽量不要进行修改。最好的方式是:重新定义一个新的类,来重复利用其中共性的内容,并且添加或者改动新的内容。

例如:若干年前的手机,只能打电话,发短信,来电显示只能显示号码,而今天的手机在来电显示的时候,不仅仅可以显示号码,还可以显示头像,地区等。在这个过程当中,我们不应该在原来老的类上进行修改,因为原来的类,可能还在有用户使用,正确做法是:新建一个新手机的类,对来电显示这个方法重写就好了,这样就达到了我们当今的需求了。


静态绑定:也称为前期绑定(早绑定),即在编译时,根据用户所传递实参类型就确定了具体调用那个方法。典型代表:函数重载。
动态绑定:也称为后期绑定(晚绑定),即在编译时,不能确定方法的行为,需要等到程序运行时,才能够确定具体调用那个类的方法。

4. 向上转移和向下转型


4.1 向上转型

向上转型:实际就是创建一个子类对象,将其当成父类对象来使用。
语法格式:父类类型 对象名 = new 子类类型()

Animal dog = new Animal("辣条", 1);

animal是父类类型,但可以引用一个子类对象,因为是从小范围向大范围的转换。

向上转型有三种使用场景:

  1. 直接赋值
Animal dog = new Animal("辣条", 1);
  1. 作为方法的参数
public class Test {
    public static void func(Animal animal){
        animal.eat();
    }
    public static void main(String[] args) {
        Animal dog = new Animal("辣 条", 1);
        func(dog);
    }
}
  1. 作为方法的返回值
public class Test {
    public static Animal func1(Animal animal){
        return animal;
    }
    public static void main(String[] args) {
        Animal dog = new Animal("辣条", 1);
        func1(dog);
    }
}

向上转型的优点:让代码实现更简单灵活。

向上转型的缺陷:不能调用到子类特有的方法。
当进行向上转型时,实际上在内存中创建的是子类对象,但通过父类引用去访问。父类引用只能访问父类中定义的成员变量和方法在内存中的部分。子类特有的成员变量和方法在内存中的部分对于父类引用来说是不可见的。

4.2 向下转型

将一个子类对象经过向上转型之后当成父类方法使用,再无法调用子类的方法,但有时候可能需要调用子类特有的方法,此时:将父类引用再还原为子类对象即可,即向下转换。
Animal类:

public class Animal {
    public String name;
    public int age;
}

Dog类:

public class Dog extends Animal{
    public void bark(){
        System.out.println(this.name + "正在汪汪叫.....");
    }
}

Bird类:

public class Bird extends Animal{
    public void fly(){
        System.out.println(this.name + "正在飞......");
    }
}

Test类:

public class Test {
    public static void main(String[] args) {
        Animal animal = new Dog();
        Animal animal1 = new Animal();
        Bird bird = new Bird();

        Dog dog =(Dog) animal;//安全的向下转型
        // 因为animal本来就是狗,只不过是将其指向了Animal

        bird = (Bird) animal1;
        //不安全的向下转型
        //animal 本来是一个动物,它不一定是一个鸟。
        //该语句可以通过编译,但是运行时会报类型转换异常 java.lang.ClassCastException:
    }
}

向下转型用的比较少,而且不安全,万一转换失败,运行时就会抛异常。Java中为了提高向下转型的安全性,引入了instanceof,如果该表达式为true,则可以安全转换。

public class Test {
    public static void main(String[] args) {
        Animal animal = new Dog();
        Animal animal1 = new Animal();
        Bird bird = new Bird();

        if(animal instanceof Dog){
            Dog dog =(Dog) animal;
            dog.bark();
        }else {
            System.out.println("animal 没有引用Dog实例");
        }

        if (animal instanceof Bird){
            bird = (Bird) animal1;
            bird.fly();
        }else {
            System.out.println("animal 没有引用Bird实例");
        }
    }
}
输出结果:
       null正在汪汪叫.....
	   animal 没有引用Bird实例 

在这里插入图片描述

5. 多态的优缺点

现有以下类:

Shape类:

public class Shape {
    public Shape() {
        System.out.println("画一个图形.....");
    }
}

Circle类:

public class Circle extends Shape{
    public Circle(){
        System.out.println("画一个⚪.....");
    }
}

Triangle类:

public class Triangle extends Shape{
    public Triangle(){
        System.out.println("画一个▲....");
    }
}

Rect类:

public class Rect extends Shape{
    @Override
    public void draw() {
        System.out.println("画一个长方形");
    }
}

现在有一个需求:打印三个⚪,一个▲

//方法1:使用循环

public class Test {
    public static void main(String[] args) {
        Circle circle = new Circle();
        Triangle triangle = new Triangle();
        String shapes[] = new String[]{"Circle", "Circle", "Circle", "Triangle"};
        for (String shape:shapes) {
            if(shape.equals("Circle")){
                circle.draw();
            }
            if (shape.equals("Triangle")){
                triangle.draw();
            }
        }
    }
}
输出结果:	
		画一个⚪
		画一个⚪
		画一个⚪
		画一个▲.....

//方法1:使用多态

public class Test {
    public static void main(String[] args) {
        Circle circle = new Circle();
        Triangle triangle = new Triangle();
        Shape shapes[] = new Shape[]{circle, circle, circle, triangle};
        for (Shape shape:shapes) {
            shape.draw();
        }
    }
}
输出结果:	
		画一个⚪
		画一个⚪
		画一个⚪
		画一个▲.....

【使用多态的好处】:
1. 能够降低代码的 “圈复杂度”, 避免使用大量的 if - else

什么叫 “圈复杂度” ?
圈复杂度是一种描述一段代码复杂程度的方式. 一段代码如果平铺直叙, 那么就比较简单容易理解. 而如果有很多的条件分支或者循环语句, 就认为理解起来更复杂.
因此我们可以简单粗暴的计算一段代码中条件语句和循环语句出现的个数, 这个个数就称为 “圈复杂度”.
如果一个方法的圈复杂度太高, 就需要考虑重构.
不同公司对于代码的圈复杂度的规范不一样. 一般不会超过 10 .

  1. 可扩展能力更强
    如果要新增一种新的形状, 使用多态的方式代码改动成本也比较低.
public class Test {
    public static void main(String[] args) {
        Circle circle = new Circle();
        Triangle triangle = new Triangle();
        Rect rect = new Rect();
        Shape shapes[] = new Shape[]{circle, circle,rect, circle, triangle};
        for (Shape shape:shapes) {
            shape.draw();
        }
    }
}
输出结果:
		画一个⚪
		画一个⚪
		画一个长方形
		画一个⚪
		画一个▲.....

在这里插入图片描述

6. 避免在构造方法中调用重写的方法

一段有坑的代码. 我们创建两个类, B 是父类, D 是子类. D 中重写 func 方法. 并且在 B 的构造方法中调用 func

B类:

public class B {
    public B(){
        func();
    }
    public void func(){
        System.out.println("父类B的func()...");
    }
}

D类:

public class D extends B{
    private int num = 1;
    public void func(){
        System.out.println("子类D的func" + num);
    }
}

Test类:

public class Test {
    public static void main(String[] args) {
        D d = new D();
    }
}
输出结果:
		子类D的func0
  • 构造 D 对象的同时, 会调用 B 的构造方法.
  • B 的构造方法中调用了 func 方法, 此时会触发动态绑定, 会调用到 D 中的 func
  • 此时 D 对象自身还没有构造, 此时 num 处在未初始化的状态, 值为 0. 如果具备多态性,num的值应该是1.
  • 所以在构造函数内,尽量避免使用实例方法,除了final和private方法。

结论: “用尽量简单的方式使对象进入可工作状态”, 尽量不要在构造器中调用方法(如果这个方法被子类重写, 就会触发动态绑定, 但是此时子类对象还没构造完成), 可能会出现一些隐藏的但是又极难发现的问题.