继承和多态的代码示例
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)); } }
相关文章推荐
- Baskets of Gold Coins Time Limit: 1000/1000 MS (Java/Others) Memory Lim
- Qt的多线程编程注意事项
- C++ 虚函数&纯虚函数&抽象类&接口&虚基类
- django 常用 模板过滤器
- c++函数返回值的引用
- Spring 3整合Quartz 2实现定时任务二:动态添加任务
- Java poi 替换 word docx文件
- Spring MVC 起步
- 详解C++中的一维数组和二维数组
- C语言中的内存分布
- 隔一个月生兔子的C语言实现
- c/c++中几个重要的指针概念
- C++父类,不能缺的虚析构函数
- java GC
- 深入理解c++枚举法
- 实现两个大数相加!
- 最简单的POI操作Excel的应用
- python学习——yield
- java-LinkedHashMap和LinkedHashSet源码分析
- Java学习笔记---设计模式工厂方法模式