参数都是Pet类的子类
可否使用一个feed(Pet pet)实现对所有宠物的喂食?
使用多态实现思路
- 编写父类
- 编写子类,子类重写父类方法
- 运行时,使用父类的类型,子类的对象
Pet pet = new Dog();
使用父类作为方法形参实现多态
public class Master {
//使用父类作为方法形参
public void feed( Pet pet ) {
pet.eat();
}
}
Pet pet = new Dog();
Master master = new Master();
master.feed( pet );//同一种操作方式,不同的操作对象
习题示例
public abstract class MotoVehicle {
private String no;//车牌号
private String brand;//品牌
abstract int calRent(int days);//计算租金
public MotoVehicle()
{
}
public MotoVehicle(String no, String brand)
{
this.no = no;
this.brand = brand;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
}
public class Car extends MotoVehicle{
public Car(String no, String brand)
{
super(no,brand);
}
@Override
int calRent(int days) {
if(getBrand().equals("宝马"))
{
return 500 * days;
}
else
{
return 600 * days;
}
}
}
public class Kache extends MotoVehicle {
private int dunwei;//吨位
public Kache(int dunwei)
{
this.dunwei = dunwei;
}
@Override
int calRent(int days) {
return 50*dunwei*days;
}
}
不用多态的实现方式
Car[] cars = new Car[3];
cars[0] = new Car("辽A12345","宝马");
cars[1] = new Car("辽B22222","别克");
cars[2] = new Car("辽A62222","奔驰");
Kache[] kaches = new Kache[2];
kaches[0] = new Kache(1);//150
kaches[1] = new Kache(4);//600
int total = 0;
for(int i = 0; i < cars.length; i++)
{
total += cars[i].calRent(3);
}
for(int i = 0; i < kaches.length; i++)
{
total += kaches[i].calRent(3);
}
System.out.println("总租金" + total);//5850
使用多态实现
MotoVehicle[] motoVehicles = new MotoVehicle[5];
motoVehicles[0] = new Car("辽A12345","宝马");
motoVehicles[1] = new Car("辽B22222","别克");
motoVehicles[2] = new Car("辽A62222","奔驰");
motoVehicles[3] = new Kache(1);
motoVehicles[4] = new Kache(4);
int total = 0;
for(int i = 0; i < motoVehicles.length; i++)
{
total += motoVehicles[i].calRent(3);
}
System.out.println("总租金" + total);
作者:豆约翰
链接:https://www.jianshu.com/p/3bacbcb9bdec
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。