❶ 用java創建一個汽車類(Car),為其定義兩個屬性:顏色和型號,為該類創建兩個構造方法
public class Car {
private int color; // 顏色 0:未定義 1:紅 2:黃 3:藍 ...
private int type ; // 型號 0:未定義 1:轎車 2:卡車 3:大巴 4:越野車
// 無形參的構造方法
public Car(){
this.type = 1;
this.color = 1;
}
// 有形參的構造方法
public Car(int type, int color ){
this.type = type;
this.color = color;
}
// 顯示顏色
public void PrintColor(){
String strColor = "";
switch(this.color){
default:
case 0:
strColor = "未定義顏色";
break;
case 1:
strColor = "紅";
break;
case 2:
strColor = "黃";
break;
case 3:
strColor = "藍";
break;
}
System.out.print(strColor);
}
// 顯示型號
public void PrintType(){
String strType = "";
switch(this.type){
default:
case 0:
strType = "未定義型號";
break;
case 1:
strType = "轎車";
break;
case 2:
strType = "卡車";
break;
case 3:
strType = "大巴";
break;
case 4:
strType = "越野車";
break;
}
System.out.print(strType);
}
}