/*
用抽象類別建立車子的類別,並建立子類別覆寫抽象類別
產生實體物件並給值實現
*/
package hw_02;
//建立車子的類別
abstract class Car {
String name; //名稱
String color; //顏色
int tire; //輪胎數
public Car(String name, String color, int tire) {
this.name=name;
this.color = color;
this.tire = tire;
}
public String getName() { //取得名稱資訊
return name;
}
public String getColor() { //取得顏色資訊
return color;
}
public int getTire() { //取得輪胎數
return tire;
}
public abstract String show(); //顯示資訊
}
//bus的類別
class Bus extends Car {
private int people; //載客數
public Bus(String name, String color, int tire, int people) {
super(name, color, tire); //呼叫CAR類別中的建構方法
this.people = people;
}
public void setPeople() { //載客數的建構式set
this.people = people;
}
public int getPeople() { //載客數的建構式get
return people;
}
public String getName() {
return name;
}
public String getColor() {
return color;
}
public int getTire() {
return tire;
}
public String show() {
return "車名:" + super.getName() + " 顏色:" + super.getColor() + " 輪胎數:" + super.getTire() + " 載客數:" + this.getPeople() + "人";
}
}
//賓士的類別
class Benz extends Car {
private int power; //馬力
public Benz(String name, String color, int tire, int power) {
super(name, color, tire);
this.power = power;
}
public void setPower() {
this.power = power;
}
public int getPower() {
return power;
}
public String getName() {
return name;
}
public String getColor() {
return color;
}
public int getTire() {
return tire;
}
public String show() {
return "車名:" + super.getName() + " 顏色:" + super.getColor() + " 輪胎數:" + super.getTire() + " 馬力:" + this.getPower() + "匹";
}
}
//腳踏車的類別
class Giant extends Car {
private int price; //價錢
public Giant(String name, String color, int tire, int price) {
super(name, color, tire);
this.price = price;
}
public void setPrice() {
this.price = price;
}
public int getPrice() {
return price;
}
public String getName() {
return name;
}
public String getColor() {
return color;
}
public int getTire() {
return tire;
}
public String show() {
return "車名:" + super.getName() + " 顏色:" + super.getColor() + " 輪胎數:" + super.getTire() + " 價錢:" + this.getPrice() + "元";
}
}
public class Hw_02 {
public static void main(String[] args) {
// TODO code application logic here
Bus bus = new Bus("統聯", "綠色", 12, 40); //產生實體物件並給值
System.out.println(bus.show()); //秀出資料
Benz benz = new Benz("賓士", "紅色", 4, 300);
System.out.println(benz.show());
Giant giant = new Giant("捷安特", "藍色", 2, 50000);
System.out.println(giant.show());
}
}
執行結果:
車名:統聯 顏色:綠色 輪胎數:12 載客數:40人
車名:賓士 顏色:紅色 輪胎數:4 馬力:300匹
車名:捷安特 顏色:藍色 輪胎數:2 價錢:50000元
留言列表