您的位置:首页 > 编程语言

继承和多态的代码示例

2015-09-12 16:25 399 查看
父类
// 抽象方法
// 抽象类 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));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: