【Java】多态

多态

1.1 多态的概念

多态的概念:通俗来说,就是多种形态,具体点就是去完成某个行为,当不同的对象去完成时会产生出不同 的状态。也就是说:同一件事情,发生在不同对象身上,就会产生不同的结果。

比如说:打印机打印,彩色打印机和黑白打印机,虽说都是打印,但是前者打印出来的是彩色的,而后者打印出来的则是黑白色的。都是打印,但是结果不同。

1.2 多态的实现环境

在java中要实现多态,是必须要满足如下三个条件,缺一不可:
1. 必须在继承体系下;
2. 子类必须要对父类中方法进行重写;
3. 通过父类的引用调用重写的方法。
多态体现:在代码运行时,当传递不同类对象时,会调用对应类中的方法。

1.3 向上转移和向下转型

1.3.1 向上转型

class Animal {
    public String name;
    public int age;
    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Animal{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
    public void eat() {

        System.out.println(name+"吃饭!");
    }
}

class Cat extends Animal {
    public Cat(String name, int age) {
        super(name, age);
    }
    public void play() {
        System.out.println(name + "正在玩耍!");
    }

}

class Bird extends Animal {
    public String swing;
    public Bird(String name,int age) {
        super(name,age);
    }
    public void fly() {
        System.out.println(name+"正在飞!");
    }

}

public class TestDemo {
    public static void main(String[] args) {
        Cat cat = new Cat("mao",12);
        cat.eat();
        Bird bird = new Bird("niao",13);
        bird.eat();
        bird.fly();

        Animal animal = new Animal("animal",14);
        animal.eat();
        //animal.fly(); // 一个引用  掉用了那个方法,要看当前的引用的类型

    }
}

我们会发现如果父类和引用一个子类的类,我们发现编程报错了;那么该如何解决这个问题呢?

这时候就要用到向上转型了。

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

public class TestDemo {

    public static void main(String[] args) {
        
        Animal animal1 = new Cat("猫猫",33);
        Animal animal2 = new Bird("小鸟",44);
        //此时我们发现可以正常运行了。
    }

}

这样的话,我们就可以轻松实现这些问题了。

向上转型的时机:

1.直接赋值;

2.函数传参;

3.函数的返回值。

public class TestDemo {

    //2.函数传参
    public static void func(Animal animal) {

    }

    //3.作为返回值
    public static Animal func2() {
        int a = 1;
        if (a == 1){
            return new Cat("猫猫",33);
        } else {
            return new Bird("小鸟", 44);
        }
    }

    public static void main2(String[] args) {

        Cat cat = new Cat("mao",12);
        func(cat);
    //1.直接赋值
        Animal animal1 = new Cat("猫猫",33);
        Animal animal2 = new Bird("小鸟",44);

    }
}

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

1.3.2 向下转型

将一个子类对象经过向上转型之后当成父类方法使用,再无法调用子类的方法,但有时候可能需要调用子类特有的方法,

此时:将父类引用再还原为子类对象即可,即向下转换。

public static void main(String[] args) {
        Animal animal2 = new Bird("小鸟2号",44);
        Bird bird = (Bird)animal2;
        bird.fly();
        
        //没调用出来,因为向下转型不安全。    不是所有的动物都会飞
        Animal animal1 = new Cat("小猫2号",33);
        Bird bird1 = (Bird) animal1;
        bird1.fly();
        
    }

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

1.4 重写

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

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

}

class Cat extends Animal {

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

    public void play() {
        System.out.println(name + "正在玩耍!");
    }
}

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

    public void fly() {
        System.out.println(name+"正在飞!");
    }

}

public class TestDemo {

    public static void main(String[] args) {
        Animal animal1 = new Cat("猫猫",33);
        animal1.eat();
        Animal animal2 = new Bird("小鸟",44);
        animal2.eat();
        //animal2.fly();//父类只能引用自己成员。

    }

-----》结果 

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAVGhlRGV2aWNl,size_20,color_FFFFFF,t_70,g_se,x_16

 此时,我们在子类的Cat与Bird里面各写一个eat方法。

class Cat extends Animal {

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

    public void play() {
        System.out.println(name + "正在玩耍!");
    }
    public void eat() {
        System.out.println(name+"吃饭!"+"::Cat");
    }

}

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

    public void fly() {
        System.out.println(name+"正在飞!");
    }

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

-------》结果 

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAVGhlRGV2aWNl,size_20,color_FFFFFF,t_70,g_se,x_16

我们发现此时,animal调用的是各自子类的方法。

这就是重写了。

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


我们将这种,父亲引用 引用子类对象,并且通过父类引用调用父类和子类的同名的覆盖方法,结果就是 可以调用子类方法。我们将这叫做动态绑定。 

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

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

【重写和重载的区别】

watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAVGhlRGV2aWNl,size_20,color_FFFFFF,t_70,g_se,x_16

《注意》

在重写中,协变类型也不报错。即返回值是父子关系的。

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

 1.5 多态的优缺点

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

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

例如我们现在需要打印的不是一个形状了,而是多个形状。如果不基于多态,我们在里面会用到大量的if - else语句。

public static void drawShapes() {
  Rect rect = new Rect();
  Cycle cycle = new Cycle();
  Flower flower = new Flower();
  String[] shapes = {"cycle", "rect", "cycle", "rect", "flower"};
 
  for (String shape : shapes) {
    if (shape.equals("cycle")) {
      cycle.draw();
   } else if (shape.equals("rect")) {
      rect.draw();
   } else if (shape.equals("flower")) {
      flower.draw();
   }
 }
}

 ======》使用多态后

public static void drawShapes() {
  Shape[] shapes = {new Cycle(), new Rect(), new Cycle(),
           new Rect(), new Flower()};
  for (Shape shape : shapes) {
    shape.draw();
 }
}

Shape[] shapes = {new Cycle(), new Rect(), new Cycle(),new Rect(), new Flower()};

这是创建了一个 Shape 对象的数组.

 2. 可扩展能力更强
如果要新增一种新的形状, 使用多态的方式代码改动成本也比较低.

多态缺陷:代码的运行效率降低。

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

这点很简单,我们可以通过这个代码直管的感受到。

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("D.func() " + num);
 }
}
public class Test {
  public static void main(String[] args) {
    D d = new D();
    //1.再这里实例化;
    //-->由于子类没有构造方法,那么子类默认一个不带参数的构造方法。此时它得先调用父类构造方法。
    //2.父类的构造方法里写了个fun();
    //-->此时应该调用父类的fun();但是子类对func();进行重写了。
    //-->此时就要直接调用子类的func();   父类的num没定义,即为0.
    //-->此时就输出----》
    // D.func() 0
 }
}

// 执行结果
D.func() 0

 

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值