通过之前的章节,我们学习了封装和继承,我们知道封装可以隐藏代码具体的实现细节,体现安全性,而继承可以实现代码的复用,本章我们将学习面向对象程序的第三个特征多态。
1.多态
1.1多态的概念
通俗来说,就是多种形态,具体点就是去完成某个行为,当不同的对象去完成时会产生出不同 的状态。
下面我们来说说什么是静态绑定和动态绑定
如下代码:
class Animal {
public String name;
public int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
System.out.println("Animal(String name, int age)");
}
public void eat() {
System.out.println(this.name+"正在吃.....");
}
}
class Dog extends Animal {
public String color;
public Dog(String name,int age,String color) {
//调用父类的 带有2个参数的构造方法 来初始化父类当中成员 必须在第一行 所以,super()和this() 是不能同时存在的
super(name,age);
this.color = color;
System.out.println("Dog(String name,int age,String color)");
}
public void barks() {
System.out.println(this.name+" 正在叫.....");
}
public void eat() {
System.out.println(this.name+" 正在吃狗粮......");
}
}
public class Test {
public static void main(String[] args) {
//父类引用 引用了子类对象
Animal animal = new Dog("旺财",2,"红色");
animal.eat();
//animal.barks();//通过Animal这个引用 只能调用Animal自己的属性
}
public static void main1(String[] args) {
Dog dog = new Dog("旺财",2,"红色");
dog.eat();
dog.barks();
Animal animal = new Animal("动物",3);
animal.eat();
//animal.barks();//通过Animal这个引用 只能调用Animal自己的属性
}
}
通过结果我们可以看到父类调用的eat方法是子类的方法,而不是自己的eat方法,为什么会出现这种情况呢?其实这里面就发生了动态绑定,在这之前我们先讲一讲什么是向上转型,向上转型就是创建了一个子类对象,将其当成父类对象来使用(下文我将进行详细讲解)
而动态绑定:就是****在编译时,不能确定方法的行为,需要等到程序运行时,才能够确定具体调用哪一个类的方法,如上面的代码,在编译时不能确定调用父类的eat方法还是子类的eat方法,当程序运行后通过父类引用调用了子类和父类相同的eat方法,此时调用的是子类的eat方法,绑定到了子类身上,这种行为就叫动态绑定
静态绑定:就是在编译时根据用户传递的参数类型就确定了具体调用哪个方法,比如函数重载。
这是理解多态的基础。
1.2多态实现条件
在java中要实现多态,必须要满足如下几个条件,缺一不可:
1. 必须在继承体系下
2. 子类必须要对父类中方法进行重写
3. 通过父类的引用调用重写的方法
多态体现:在代码运行时,当传递不同类对象时,会调用对应类中的方法
class Dog extends Animal {
public String color;
public Dog(String name,int age,String color) {
super(name,age);
this.color = color;
//System.out.println("Dog(String name,int age,String color)");
}
public void barks() {
System.out.println(this.name+" 正在叫.....");
}
public void eat() {
System.out.println(this.name+" 正在吃狗粮......");
}
}
class Bird extends Animal {
public Bird(String name,int age) {
super(name,age);
}
public void fly() {
System.out.println(this.name +" 正在飞....");
}
public void eat() {
System.out.println(this.name+" 正在吃鸟粮....");
}
}
public class Test {
public static void main(String[] args) {
Animal animal = new Dog("旺财",2,"红色");
animal.eat();
Bird bird = new Bird("百灵",1);
Animal animal2 = bird;
animal2.eat();
}
1.3重写
重写(override):也称为覆盖。重写是子类对父类非静态、非private修饰,非final修饰,非构造方法等的实现过程进行重新编写, 返回值和形参都不能改变。即外壳不变,核心重写!重写的好处在于子类可以根据需要,定义特定于自己的行为。 也就是说子类能够根据需要实现父类的方法。
【方法重写的规则】
1.子类在重写父类的方法时,一般必须与父类方法原型一致: 返回值类型 方法名 (参数列表) 要完全一致
2.被重写的方法返回值类型可以不同,但是必须是具有父子关系的
3.访问权限不能比父类中被重写的方法的访问权限更低。例如:如果父类方法被public修饰,则子类中重写该方法就不能声明为 protected
4.父类被static、private修饰的方法、构造方法都不能被重写。
5.重写的方法, 可以使用 @Override 注解来显式指定. 有了这个注解能帮我们进行一些合法性校验. 例如不小心将方法名字拼写错了 (比如写成 aet), 那么此时编译器就会发现父类中没有 aet 方法, 就会编译报错, 提示无法构成重写
【重写和重载的区别】
重写:
1.方法名相同。
2.参数列表相同(顺序,个数,类型)。
3.返回值相同。
重载:
1.方法名相同。
2.参数列表不同。
3.返回值不影响。
方法重载是一个类的多态性表现,而方法重写是子类与父类的一种多态性表现
1.4向上转移和向下转型
1.4.1 向上转型
语法格式:
父类类型 对象名 = new 子类类型()
Animal animal = new Dog("旺财",2,"红色");
Animal是父类类型,但可以引用一个子类对象,因为是从小范围向大范围的转换。
向上转型的三种使用场景:
- 直接赋值
- 方法传参
- 方法返回
Animal animal = new Dog("旺财",2,"红色");
animal.eat();
Bird bird = new Bird("百灵",1);
Animal animal2 = bird;
animal2.eat();
这就是直接赋值。
public class Test {
public static void fun(Animal animal){
animal.eat();
}
public static void main(String[] args) {
Dog dog = new Dog("旺财",2,"红色");
//Animal animal = dog;
//Animal animal = new Dog("旺财",2,"红色");
fun(dog);
//animal.eat();
Bird bird = new Bird("百灵",1);
fun(bird);
//Animal animal2 = bird;
// animal2.eat();
}
这是第二种通过传参
public static Animal fun2() {
return new Bird("布谷",1);
这是第三种,通过返回值,进行向上转型。
向上转型的优点:让代码实现更简单灵活。
向上转型的缺陷:不能调用到子类特有的方法。
下面我们讲讲如何避免在构造方法中调用重写的方法:
注意:当在父类的构造方法当中调用父类和子类同名的方法的时候,此时也会发生动态绑定,也意味着构造方法内也会发生动态绑定。
如下实例:
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 Test2 {
public static void main(String[] args) {
//1. 分配内存空间 2. 调用合适的构造方法
D d = new D();
}
}
从结果中我们可以看到,当我们在父类方法中调用了重写的func方法时,此时也发生了动态绑定,打印的是子类的func方法,但是为什么num还是0呢?我们明明将num的值初始化为了1.我们知道代码的执行顺序为父类的实例,父类的构造,然后才是子类的实例,子类的构造。上述代码中先执行父类的实例和父类的构造,而子类还没有进行实例,因此num的值还是为0。
1.4.2向下转型
将一个子类对象经过向上转型之后当成父类方法使用,再无法调用子类的方法,但有时候可能需要调用子类特有的方法,此时:将父类引用再还原为子类对象即可,即向下转换。
Bird bird1 = (Bird)animal2;
bird.fly();
Animal animal1 = new Dog("旺财",3,"红色");
//
if(animal1 instanceof Bird) {
Bird bird2 = (Bird) animal1;
bird2.fly();
}else {
System.out.println("hello");
}
向下转型用的比较少,而且不安全,万一转换失败,运行时就会抛异常。Java中为了提高向下转型的安全性,引入了 instanceof ,如果该表达式为true,则可以安全转换。
1.5 多态的优缺点
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("❀");
}
}
【使用多态的好处】
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"};
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 main(String[] args) {
/*Rect rect = new Rect();
Cycle cycle = new Cycle();
Triangle triangle = new Triangle();
Shape[] shapes = {cycle,rect,cycle,rect,triangle};
*/
Shape rect = new Rect();
Shape cycle = new Cycle();
Shape triangle = new Triangle();
Shape flower = new Flower();
Shape[] shapes = {cycle,rect,cycle,rect,triangle,flower};
for(Shape shape : shapes) {
shape.draw();
}
}
2. 可扩展能力更强
Shape flower = new Flower();
Shape[] shapes = {cycle,rect,cycle,rect,triangle,flower};
如果要新增一种新的形状, 使用多态的方式代码改动成本也比较低.
对于类的调用者来说, 只要创建一个新类的实例就可以了, 改动成本很低.
而对于不用多态的情况, 就要把 drawShapes 中的 if - else 进行一定的修改, 改动成本更高.
多态缺陷:代码的运行效率降低。
1. 属性没有多态性
当父类和子类都有同名属性的时候,通过父类引用,只能引用父类自己的成员属性
2. 构造方法没有多态性(详细请看上面避免在构造方法中调用重写的方法)