前言
什么叫多态? 多态就是一种事物可以有多种表现形式
多态三要素
1. 被动方必须有继承关系
2. 子类一般都要重写父类方法
3. 必须将主动方的功能函数的参数设置为 被动方父类的类型
举个例子司机开车
假如说司机会开汽车 我们需要定义个汽车的类 然后在司机类中添加会开汽车的的方法
假如说司机会开卡车 我们需要再定义一个卡车的类 然后在司机类中添加会开卡车的方法下面看下传统的调用方式 代码如下:
- class Car
- {
- private String name;
- // 无参 构造方法
- public Car(){}
- // 有参构造方法
- public Car(String name){
- this.name = name;
- }
- public void setName(String name){
- this.name = name;
- }
- public String getName(){
- return this.name;
- }
- public void run(){}
- }
- class Bus extends Car
- {
- public Bus(){}
- public Bus(String name){
- super(name);
- }
- public void run(){
- System.out.println("公交车在跑");
- }
- }
- class SmallCar extends Car
- {
- public SmallCar(){}
- public SmallCar(String name){
- super(name);
- }
- public void run(){
- System.out.println("小轿车在跑");
- }
- }
- class Drivers
- {
- // 假如司机会开公交车
- public void driverBus(Bus b){
- b.run();
- }
- // 假如司机会开小轿车
- public void driverSmallCar(SmallCar smcar){
- smcar.run();
- }
- }
- class TestDt
- {
- public static void main(String[] args)
- {
- Drivers d = new Drivers();
- // 司机开公交车
- d.driverBus(new Bus("公交车"));
- d.driverSmallCar(new SmallCar("小轿车"));
- }
- }
正如上面的列子 在添加司机开其他的车 就会重复上面的行为 缺点是 扩展性比较差, 后期代码维护困难.
然后我们用多态的写法优化上述例子 代码如下:
- class Car
- {
- private String name;
- // 无参 构造方法
- public Car(){}
- // 有参构造方法
- public Car(String name){
- this.name = name;
- }
- public void setName(String name){
- this.name = name;
- }
- public String getName(){
- return this.name;
- }
- public void run(){}
- }
- class Bus extends Car
- {
- public Bus(){}
- public Bus(String name){
- super(name);
- }
- public void run(){
- System.out.println("公交车在跑");
- }
- }
- class SmallCar extends Car
- {
- public SmallCar(){}
- public SmallCar(String name){
- super(name);
- }
- public void run(){
- System.out.println("小轿车在跑");
- }
- }
- class Drivers
- {
- public void driverCar(Car car){
- car.run();
- }
- }
- class TestDt
- {
- public static void main(String[] args)
- {
- Drivers d = new Drivers();
- d.driverCar(new Bus("公交车"));
- d.driverCar(new SmallCar("小轿车"));
- }
- }
比较第一种写法 假如司机还会开其他的车 只需要添加会开这种车的类就行 司机类不需要再添加其它功能方法 . 代码简介 后期维护比较方便 这种编写多态的形式也叫向上转型.
来源: http://www.bubuko.com/infodetail-2550900.html