多态的概念
多态的概念:通俗来说,就是多种形态,具体点就是去完成某个行为,当不同的对象去完成时会产生出不同的状态。
多态实现的条件
1. 必须在继承体系下
2. 子类必须要对父类中方法进行重写
3. 通过父类的引用调用重写的方法
多态体现:在代码运行时,当传递不同类对象时,会调用对应类中的方法。
public class Test {
public static void eat(Animal a) {
a.eat();
}
public static void main(String[] args) {
Animal.Cat cat=new Animal.Cat("小咪",3);
eat(cat);
Animal.Dog dog=new Animal.Dog("旺财",6);
eat(dog);
}
}
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 + "正在吃东西");
}
public static class Dog extends Animal {
public Dog(String name, int age) {
super(name, age);
}
public void eat() {
System.out.println(name + "正在吃狗粮~~~");
}
}
public static class Cat extends Animal {
public Cat(String name, int age) {
super(name, age);
}
public void eat() {
System.out.println(name + "正在吃猫粮~~~");
}
}
}
多态的优缺点
优点
1. 能够降低代码的 “圈复杂度”, 避免使用大量的 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 对象的数组.
Shape[] shapes = {new Cycle(), new Rect(), new Cycle(),
new Rect(), new Flower()};
for (Shape shape : shapes) {
shape.draw();
}
}
2. 可扩展能力更强
如果要新增一种新的形状, 使用多态的方式代码改动成本也比较低
class Triangle extends Shape {
@Override
public void draw() {
System.out.println("△");
}
}
缺点
1. 属性没有多态性
当父类和子类都有同名属性的时候,通过父类引用,只能引用父类自己的成员属性
2. 构造方法没有多态性