package car; public class Vehicle { //定義成員變量 private int wheels; private double weight; public int getWheels() { return wheels; } public void setWheels(int wheels) { this.wheels = wheels; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } //構造方法 public Vehicle(int wheels, double weight) { super(); this.wheels = wheels; this.weight = weight; } }
package car; public class Car extends Vehicle { // 定義新的成員變量 private int loader; public int getLoader() { return loader; } public void setLoader(int loader) { this.loader = loader; } // 調用父類構造方法 public Car(int wheels, double weight,int loader) { super(wheels, weight); this.loader=loader; } }
package car; public class Truck extends Car { //添加新的成員變量 private double payload; public double getPayload() { return payload; } public void setPayload(double payload) { this.payload = payload; } //調用父類構造方法 public Truck(int wheels, double weight, int loader, double payload ) { super(wheels, weight, loader); this.payload=payload; } }
package car; public class Text_car { public static void main(String[] args) { //實例化Vehicle對象 Vehicle v= new Vehicle(4,2); System.out.println("汽車A有"+v.getWheels()+"個輪子,它的重量是"+v.getWeight()+"噸"); //實例化car對象 Car c = new Car(8,2,20); System.out.println("汽車B有"+c.getWheels()+"個輪子,它的重量是"+c.getWeight()+"噸,能載"+c.getLoader()+"個人"); //實例化Truck對象 Truck t= new Truck(8,3,4,10); System.out.println("汽車C有"+t.getWheels()+"個輪子,它的重量是"+t.getWeight()+"噸,能載"+t.getLoader()+"個人,能裝"+t.getPayload()+"噸貨"); } }