继承和多态的代码示例

父类
// 抽象方法
// 抽象类 abstract
public abstract class Vehicle {
	private String no;
	private String brand;
	private String color;
	private float mileage;

	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 String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

	public float getMileage() {
		return mileage;
	}

	public void setMileage(float mileage) {
		this.mileage = mileage;
	}

	// 必须有一个空构造方法
	public Vehicle() {
		super();
	}

	public Vehicle(String no) {
		super();
		this.no = no;
	}

	// 抽象方法 abstract
	// 抽象类
	public abstract float calRent(int day);

}


子类

public class Car extends Vehicle {
	private String type;

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public Car() {
		super();
	}

	public Car(String no, String type) {
		super(no);
		this.type = type;
	}

	public float calRent(int days) {
		switch (type) {
		case "gl8":
			return 600 * days;
		case "550i":
			return 500 * days;
		case "bk":
			return 300 * days;

		}
		return 0;
	}

}

子类


public class Bus extends Vehicle {
	private int seartCount;

	public int getSeartCount() {
		return seartCount;
	}

	public void setSeartCount(int seartCount) {
		this.seartCount = seartCount;
	}

	public Bus() {
		super();
	}

	public Bus(String no, int seartCount) {
		super(no);
		this.seartCount = seartCount;
	}

	public float calRent(int days) {
		if (seartCount <= 16)
			return 800 * days;
		else
			return 1500 * days;

	}
}

测试类

public class Test {
	public static void main(String[] args) {
		Car car = new Car("11111", "bk");
		System.out.println(car.calRent(10));

		Bus bus = new Bus("22222", 19);
		System.out.println(bus.calRent(10));

		// 多态:多种形态 程序执行结果随着父类变量指向的不同而改变
		// 子类对象可以直接赋值给父类变量
		Vehicle vehicle = new Car("11111", "gl8");
		System.out.println(vehicle.calRent(10));
		Vehicle vehicle2 = new Bus("2222", 6);
		System.out.println(vehicle2.calRent(10));
	}

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值