java中多态的使用

多态的概念

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

多态实现的条件

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. 构造方法没有多态性

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值