多态 一种类型的多种状态 还有一个小汽车的例子再理解下
汽车接口(相当于父类)
package com.oop.demo10;
public interface Car {
String getName();
int getMoney();
}
宝马车(子类)
package com.oop.demo10;
public class BWM implements Car {
@Override
public String getName() {
return "宝马车";
}
@Override
public int getMoney() {
return 1000000;
}
}
奥迪车(子类)
package com.oop.demo10;
public class Audi implements Car {
@Override
public String getName() {
return "奥迪";
}
@Override
public int getMoney() {
return 200000;
}
}
4S店
package com.oop.demo10;
public class CarShop {
public int total = 0;
/*
* 这里并不知道具体的car是什么
* 比如 宝马 奥迪 大众 奔驰等等
* 只能等到运行时期才会知道
* 不需要关心是什么具体的车
* 只跟car打交道就好了
* 这就是多态 一个car有很多种类型
* 不需要像以前那样 if 是 宝马 多少钱 奔驰 多少钱等等进行操作
* 非常的动态化 不到运行时期 不知道是哪一款车
* */
public void sellCar(Car car) {
System.out.println("车辆名称是== \t" + car.getName());
total += car.getMoney();
}
public int getTotal(){
return this.total;
}
}
测试类
package com.oop;
import com.oop.demo10.Audi;
import com.oop.demo10.BWM;
import com.oop.demo10.CarShop;
public class Applcation {
public static void main(String[] args) {
CarShop carShop = new CarShop();
carShop.sellCar(new BWM());
System.out.println(carShop.getTotal());
System.out.println("=====================");
carShop.sellCar(new Audi());
System.out.println(carShop.getTotal());
}
}
结果
原文:https://www.cnblogs.com/juanbao/p/15016240.html