不就是Java吗之多态

2.1 多态的概念

多态,字面意思就是多种形态,实际上就是同一个行为具有多个不同表现形式或形态的能力。

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

比如:

这是一个打印机,去打印照片;彩色打印机打印出来的就是彩色的照片,黑白打印机打印出来的就是黑白的照片;它们完成的动作都是打印,但是实现了不同的效果,这就是一种多态。

或者,比如吃饭这个动作。猫就吃猫粮,狗就吃狗粮,他们进行的都是吃饭的动作,但是吃饭的结果不同(一个猫粮,一个狗粮),这也是一种多态。

image-20220528224650292

总的来说:同一件事情,发生在不同对象身上,就会产生不同的结果。

2.2 多态的实现条件

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

  1. 必须在继承体系下

  2. 子类必须要对父类中方法进行重写

    右键->generate->Override Methods

  3. 通过父类的引用调用重写的方法

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

Animal.java:

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 + "吃饭");
    }
}

//1.必须在继承的体系下
class Cat extends Animal {
    public Cat(String name, int age) {
        super(name, age);
    }

    //2.子类必须要对父类中的方法进行重写
    //右键->Generate->Override Methods
    @Override
    public void eat() {
        super.eat();
    }
}

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

    @Override
    public void eat() {
        super.eat();
    }
}

TestAnimal.java

public class TestAnimal {
    // 编译器在编译代码时,并不知道要调用Dog 还是 Cat 中eat的方法
  	// 等程序运行起来后,形参a引用的具体对象确定后,才知道调用那个方法
  	// 注意:此处的形参类型必须时父类类型才可以
    
    //3.通过父类的引用调用重写的方法
    public static void eat(Animal animal) {
        animal.eat();
    }
    public static void main(String[] args) {
        Cat cat = new Cat("咪咪",3);
        Dog dog = new Dog("卡路里",3);

        eat(cat);
        eat(dog);
    }
}

image-20220529102719060

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

image-20220529103233291

2.3 多态的三方面

我们先看一段代码:

class Animal {
    public String name;
    public int age;

    public void eat() {
        System.out.println(this.name + "吃饭!");
    }
}

class Cat extends Animal {
    public String hair;

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

public class TestDemo {
    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.eat();//cat对象可以使用父类的方法
        cat.mew();//cat对象也可以使用子类自己的方法
    }
}

image-20220528230900031

那么既然子类可以访问父类的成员变量以及成员方法,那么我定义一个父类,他能不能访问子类的成员变量以及成员方法呢?

class Animal {
    public String name;
    public int age;

    public void eat() {
        System.out.println(this.name + "吃饭!");
    }
}

class Cat extends Animal {
    public String hair;

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

public class TestDemo {
    public static void main(String[] args) {
        Animal animal = new Animal();
        animal.eat();//animal对象可以访问父类自己的方法
        animal.mew();//animal对象访问不了子类的方法
    }
}

image-20220528230915340

我们可以得知:父类对象只能访问自己的成员

那么接下来,给大家讲解一下向上转型:

2.3.1 向上转型

向上转型,其实就是创建一个子类对象,把他当成父类对象用

语法:

父类类型 对象名 = new 子类类型();
//Animal animal = new Cat();

image-20220528231233941

三种常见的向上转型:

  1. 直接赋值
  2. 方法的参数
  3. 方法的返回值
2.3.1.1 直接赋值
public static void main2(String[] args) {
    //方式1:
    Cat cat = new Cat();
	Animal animal = cat;//父类引用 引用了 子类的对象
    
    //方式2:
    Animal animal = new Cat();//向上转型
   
}

那么这时父类还是不能访问子类的成员变量/成员方法,因为animal的类型还是Animal,父类只能访问自己的成员方法/成员属性

public static void main(String[] args) {
        Animal animal = new Cat();
        animal.name = "傲娇";
        animal.age = 22;
        animal.eat();
        animal.mew();//还是访问不了子类的成员属性/成员方法
    }

image-20220528231845676

总结:向上转型,就是把原来的子类的类型转换成了父类的类型,那么之后就只能去访问父类特有的成员方法或者成员变量。

2.3.1.2 方法的参数
public static void func(Animal animal) {

    }
    public static void main(String[] args) {
        Cat cat = new Cat();
        func(cat);
    }

func函数里面传的是子类的cat对象,func用父类的Animal对象接收,这就实现了向上转型,因为本身我们就可以用Cat cat接收,但是我们用Animal animal也可以接收,这就代表了发生了向上转型。

像这样写也是可以的

public static void func(Animal animal) {

    }
    public static void main(String[] args) {
        func(new Cat());
    }

因为new Cat()也是实例化一个Cat的对象,用Animal animal接收,发生了向上转型

2.3.1.3 方法的返回值
public static Animal func2() {
        //return new Animal();//返回Animal本身没问题
        return new Cat();//返回子类,用Animal接收,这代表发生了向上转型
    }

正常情况下,返回值是Animal,那么你返回的对象就应该是Animal类型的,但是返回Cat类型的也可以,这就代表了发生向上转型

2.2.2.4 向下转型(了解)

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

image-20220529093248152

class Animal {
    public String name;
    public int age;

    public void eat() {
        System.out.println(this.name + "吃饭!");
    }
}

class Bird extends Animal {
    @Override
    public void eat() {
        System.out.println(this.name + "正在吃鸟食!");
    }

    public void fly() {
        System.out.println(this.name + "正在飞!");
    }
}
public class TestDemo {
    public static void main(String[] args) {
        Animal animal = new Animal();
        animal.fly();
    }
}

我们可以看到,此时Animal实例化出来的对象,还是调用不了子类的方法
image-20220529092403471

那么我们这样操作呢

class Animal {
    public String name;
    public int age;

    public void eat() {
        System.out.println(this.name + "吃饭!");
    }
}

class Bird extends Animal {
    @Override
    public void eat() {
        System.out.println(this.name + "正在吃鸟食!");
    }

    public void fly() {
        System.out.println(this.name + "正在飞!");
    }
}
public class TestDemo {
    public static void main(String[] args) {
        Animal animal = new Bird();
        animal.fly();
    }
}

这样也是不可以的,现在发生了向上转型

那么接下来这个动作,我们就可以让animal飞起来~

class Animal {
    public String name;
    public int age;

    public void eat() {
        System.out.println(this.name + "吃饭!");
    }
}

class Bird extends Animal {
    @Override
    public void eat() {
        System.out.println(this.name + "正在吃鸟食!");
    }

    public void fly() {
        System.out.println(this.name + "正在飞!");
    }
}
public class TestDemo {
    public static void main(String[] args) {
        Animal animal = new Bird();
        Bird bird = (Bird)animal;//向下转型-把⽗类给子类了
        bird.fly();
    }
}

image-20220529092821559

那么向下转型危险性很高,很容易就制造出一个bug,就比如下面这样

class Animal {
    public String name;
    public int age;

    public void eat() {
        System.out.println(this.name + "吃饭!");
    }
}

class Cat extends Animal {
    public String hair;

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

class Bird extends Animal {
    @Override
    public void eat() {
        System.out.println(this.name + "正在吃鸟食!");
    }

    public void fly() {
        System.out.println(this.name + "正在飞!");
    }
}
public class TestDemo {
    public static void main(String[] args) {
        Animal animal = new Cat();
        Bird bird = (Bird)animal;
        bird.fly();
    }
}

image-20220529095009377

那么Java官方也发现了这个问题,给了一个关键字instanceof来解决这个问题

instanceof是用来判断前面这个引用 引用的对象 是不是后面那个对象的实例(animal引用的是不是bird)

public static void main(String[] args) {
        Animal animal = new Bird();
        if(animal instanceof Bird) {
            Bird bird = (Bird)animal;
            bird.fly();
        }
    }

image-20220529095540746

public static void main(String[] args) {
        Animal animal = new Cat();
        if(animal instanceof Bird) {
            Bird bird = (Bird)animal;
            bird.fly();
        }
    }

2.2.2.5 向上转型的优缺点

向上转型的优点:让代码实现更简单灵活。
向上转型的缺陷:不能调用到子类特有的方法。

2.3.2 方法重写

重写,也叫做覆盖/覆写。重写是子类对父类非静态、非private修饰,非final修饰,非构造方法等的实现过程进行重新编写, 返回值和形参都不能改变。即外壳不变,核心重写!重写的好处在于子类可以根据需要,定义特定于自己的行为。 也就是说子类能够根据需要实现父类的方法。

2.3.2.1 重写的三个条件
  1. 方法名相同
  2. 返回值相同
  3. 参数列表相同
image-20220529103752711
2.3.2.2 重写的注意事项
  1. private方法不能进行重写

    public class Animal {
        public String name;
        public int age;
    
        public Animal(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        private void eat() {
            System.out.println(this.name + "吃饭");
        }
    }
    
    class Cat extends Animal {
        public Cat(String name, int age) {
            super(name, age);
        }
    
        @Override
        public void eat() {
            System.out.println(super.name + "正在吃猫粮");
        }
    }
    
    

    image-20220529104207144

  2. 静态方法不能进行重写

    public class Animal {
        public String name;
        public int age;
    
        public Animal(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public static void eat() {
            System.out.println(name + "吃饭");
        }
    }
    
    class Cat extends Animal {
        public Cat(String name, int age) {
            super(name, age);
        }
    
        @Override
        public void eat() {
            System.out.println(super.name + "正在吃猫粮");
        }
    }
    

    image-20220529104333207

  3. final修饰的方法不可以被重写

    public class Animal {
        public String name;
        public int age;
    
        public Animal(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        final public void eat() {
            System.out.println(name + "吃饭");
        }
    }
    
    
    class Cat extends Animal {
        public Cat(String name, int age) {
            super(name, age);
        }
        
        @Override
        public void eat() {
            System.out.println(super.name + "正在吃猫粮");
        }
    }
    

    image-20220529111222591

  4. 子类的访问修饰限定符权限要大于等于父类

    权限等级:private<default<protected<public

    public class Animal {
        public String name;
        public int age;
    
        public Animal(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        protected void eat() {
            System.out.println(name + "吃饭");
        }
    }
    
    class Cat extends Animal {
        public Cat(String name, int age) {
            super(name, age);
        }
    
        //子类的访问修饰限定符权限要大于等于父类
        @Override
        public void eat() {
            System.out.println(super.name + "正在吃猫粮");
        }
    }
    

    image-20220529104725642

    public class Animal {
        public String name;
        public int age;
    
        public Animal(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        protected void eat() {
            System.out.println(name + "吃饭");
        }
    }
    
    class Cat extends Animal {
        public Cat(String name, int age) {
            super(name, age);
        }
    
        //子类的访问修饰限定符权限要大于等于父类
        @Override
        protected void eat() {
            System.out.println(super.name + "正在吃猫粮");
        }
    }
    

    image-20220529104839207

2.3.2.3 方法重写的规则
  1. 子类在重写父类的方法时,一般必须与父类方法原型一致:修饰符 返回值类型 方法名(参数列表) 要完全一致

  2. JDK7以后,被重写的方法返回值类型可以不同,但是必须是具有父子关系的

  3. 访问权限不能比父类中被重写的方法的访问权限更低。例如:如果父类方法被public修饰,则子类中重写该方
    法就不能声明为 protected

  4. 父类被staticprivate修饰的方法都不能被重写。

  5. 子类和父类在同一个包中,那么子类可以重写父类所有方法,除了声明为 privatefinal的方法。

  6. 子类和父类不在同一个包中,那么子类只能够重写父类的声明为 publicprotected 的非 final 方法。

  7. 重写的方法, 可以使用 @Override 注解来显式指定. 有了这个注解能帮我们进行一些合法性校验. 例如不小心将方法名字拼写错了 (比如写成 aet), 那么此时编译器就会发现父类中没有 aet 方法, 就会编译报错, 提示无法构成重写.

  8. 协变类型:比如返回值构成了父子类关系

    protected Animal eat() {
        
    }
    
    @Override
    protected Cat eat() {
        
    }
    
2.3.2.4 重载与重写的区别
区别重载重写
参数列表必须修改一定不能修改
返回值类型可以修改一定不能修改
访问限定符可以修改子类大于父类即可
2.3.2.5 重写的设计原则

对于已经投入使用的类,尽量不要进行修改。最好的方式是:重新定义一个新的类,来重复利用其中共性的内容,并且添加或者改动新的内容。
例如:若干年前的手机,只能打电话,发短信,来电显示只能显示号码,而今天的手机在来电显示的时候,不仅仅可以显示号码,还可以显示头像,地区等。在这个过程当中,我们不应该在原来老的类上进行修改,因为原来的类,可能还在有用户使用,正确做法是:新建一个新手机的类,对来电显示这个方法重写就好了,这样就达到了我们当今的需求了。

image-20220529115638246

2.3.2.6 动态绑定与静态绑定

动态绑定:也称为后期绑定(晚绑定),即在编译时,不能确定方法的行为,需要等到程序运行时,才能够确定具体调用那个类的方法。

静态绑定:也称为前期绑定(早绑定),即在编译时,根据用户所传递实参类型就确定了具体调用那个方法。典型代表函数重载。

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(name + "吃饭");
    }
}


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

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

public class TestAnimal {

    public static void main(String[] args) {
        Animal animal = new Cat();
        animal.name = "布朗尼";
        animal.eat();//编译的时候,这里面还是Animal的eat方法
    }
}

我们可以通过Java自带的反汇编工具查看

我们先进行编译,然后使用JDK自带的javap反汇编工具查看,具体操作如下

  1. 找到代码所在地
  2. out文件夹->production文件夹
  3. 按住shift+右键,打开Powershell窗口
  4. 输入javap -v TestMethod(文件名)

image-20220529120804031

我们可以看到,在编译期间,还是Animaleat方法,但是在运行的时候,变成了子类自己的eat方法,这就叫做动态绑定(运行时绑定),他最大的特点就是:只有在运行的时候才确定调用谁

image-20220529121132625

2.4 继承和多态的组合使用举例

问题场景:我们要实现一个类,这个类的作用是画出不一样的图案。

那么,我们的第一步就是要创建出一个类

class Shape {
    //这里我们就省略具体的属性,直接写成员方法
    public void draw() {
        System.out.println("画图案");
    }
}

那么我们创建出来的父类,并没有画出具体的图案,他只是在告诉我们现在是在画图案。

那么我们可以创建出不同的关于图案的类,来继承Shape这个类,然后就可以进行重写了

class Cycle extends Shape {
    @Override
    public void draw() {
        System.out.println("●");
    }
}

class Rect extends Shape {
    @Override
    public void draw() {
        System.out.println("♦");
    }
}

class Triangle extends Shape {
    @Override
    public void draw() {
        System.out.println("▲");
    }
}

那么我们可以在main方法先测试一下了

public class TestDemo {
    public static void main(String[] args) {
        Shape shape = new Shape();
        shape.draw();//画图案
    }
}

image-20220530085224907

那么我们想要实现不同的打印图案呢,就需要用到多态

多态的实现条件

  1. 必须在继承体系下

  2. 子类必须要对父类中方法进行重写

    右键->generate->Override Methods

  3. 通过父类的引用调用重写的方法

public class TestDemo {
    public static void draw(Shape shape) {
        shape.draw();
    }
    public static void main(String[] args) {
        Cycle cycle = new Cycle();
        Rect rect = new Rect();
        Triangle triangle = new Triangle();

        draw(cycle);
        draw(rect);
        draw(triangle);
    }
}

image-20220530085735853

那么这样的代码对后续的更改也很友好。比如我们想要加一个打印花的图案的功能,我们只需要再创建出一个类,然后继承Shape类,对Shape里面的draw方法进行重写即可

class Flower extends Shape {
    @Override
    public void draw() {
        System.out.println("✿");
    }
}
public class TestDemo {
    public static void draw(Shape shape) {
        shape.draw();
    }
    public static void main(String[] args) {
        Cycle cycle = new Cycle();
        Rect rect = new Rect();
        Triangle triangle = new Triangle();

        draw(cycle);
        draw(rect);
        draw(triangle);
        draw(new Flower());//这里,我们采用这种初始化的方式,也是可以的。但是只能使用一次,再次使用需要再次new一下
    }
}

image-20220530090051304

全部代码在这:

class Shape {
    //这里我们就省略具体的属性,直接写成员方法
    public void draw() {
        System.out.println("画图案");
    }
}

class Cycle extends Shape {
    @Override
    public void draw() {
        System.out.println("●");
    }
}

class Rect extends Shape {
    @Override
    public void draw() {
        System.out.println("♦");
    }
}

class Triangle extends Shape {
    @Override
    public void draw() {
        System.out.println("▲");
    }
}

class Flower extends Shape {
    @Override
    public void draw() {
        System.out.println("✿");
    }
}
public class TestDemo {
    public static void draw(Shape shape) {
        shape.draw();
    }
    public static void main(String[] args) {
        Cycle cycle = new Cycle();
        Rect rect = new Rect();
        Triangle triangle = new Triangle();

        draw(cycle);
        draw(rect);
        draw(triangle);
        draw(new Flower());
    }
    public static void main1(String[] args) {
        Shape shape = new Shape();
        shape.draw();
    }
}

2.5 多态的优缺点

优点:

  1. 能够降低代码的 “圈复杂度”, 避免使用大量的 if - else

    圈复杂度:一段代码中条件语句和循环语句出现的个数

    如果一个代码的圈复杂度过高,就要考虑重构(推倒重来)

    一般对于圈复杂度的要求,是不能超过10的

    比如我们刚刚的例子,我们想要打印多个形状的话,而且还不能用多态的思想,那么代码的实现如下

    public static void drawShapes() {
        Rect rect = new Rect();
        Cycle cycle = new Cycle();
        Flower flower = new Flower();
        String[] shapes = {"cycle", "rect", "cycle", "rect", "flower"};//定义一个String数组存放
    
        //遍历数组,如果字符串匹配,那么就执行draw方法
        for (String shape : shapes) {
            if (shape.equals("cycle")) {
                cycle.draw();
            } else if (shape.equals("rect")) {
                rect.draw();
            } else if (shape.equals("flower")) {
                flower.draw();
            }
        }
    }
    

    如果使用了多态,那么就不用写这么多的if-else了,降低了代码的圈复杂度

    public static void drawShapes() {
        Rect rect = new Rect();
        Cycle cycle = new Cycle();
        Flower flower = new Flower();
        Shape[] shapes = {cycle,rect,cycle,rect,flower};
        for (Shape shape : shapes) {
            shape.draw();
        }
    }
    
  2. 可扩展能力强:如果要新增一种新的形状, 使用多态的方式代码改动成本也比较低.

    就比如刚才,我们添加的Flower方法,就是这样。对于类的调用者来说,只需要在创建一个Flower的实例即可,改动成本很低

缺点:代码的运行效率降低(可以考虑组合)

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

我们看这段代码:

class B {
    public B() {
        func();
    }
    public void func() {
        System.out.println("B.func()");
    }
}
class D extends B {
    @Override
    public void func() {
        System.out.println("D.func() ");
    }
}
public class Test{
    public static void main(String[] args) {
        D d = new D();
    }
}

结果是D.func()

其实这段代码是长这个样子的

class B {
    public B() {
        func();
    }
    public void func() {
        System.out.println("B.func()");
    }
}
class D extends B {
    D() {
        super();
    }
    @Override
    public void func() {
        System.out.println("D.func() ");
    }
}
public class Test{
    public static void main(String[] args) {
        D d = new D();
    }
}

D里面默认会有一个不带参数的构造函数来调用B里面的构造函数。

可是类B里面的构造函数的func()不应该调用B类里面的func函数吗?咱么调用的是D类里面重写的func函数?

这就是他的离谱之处了。所以大家要避免在构造方法中调用重写的函数,以防出问题找不到

下面是它的运行的图解

image-20220530094553200

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

加勒比海涛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值