1: public static void main(String[] s1) {
2: // TODO Auto-generated method stub
3:
4: Car car1;//宣告
5: car1 = new Car();//建立(實體化)
6:
7: Car car2 = new Car();//同時宣告和建立(實體化)
8:
9: int[] i1 = new int[]{0,1,2,3};
10: NewCar nc = new NewCar(2);
11: nc.setNum(i1);
12:
13: SuperCar sc1 = new SuperCar();
14:
15: }
16:
17: }
18:
19: class Car //最基本的類別
20: {
21: Car()//建構子,不加這行也可以,編譯器會自動加上super()
22: {
23: System.out.println("in Car()");
24: }
25: }
26:
27: class NewCar
28: {
29:
30: int carType;//屬性成員
31: String carSize;//屬性成員
32:
33: NewCar()//建構子1 overloading ,沒有回傳值,名稱和類別相同
34: {
35: //this(0,"Small"); 呼叫建構子3 ,作用和下2行相同
36: carType = 0;
37: this.carSize = "Small";//使用this
38:
39: }
40:
41: NewCar(int type)//建構子2 overloading
42: {
43:
44: System.out.println("in NewCar(int type)");
45: this.carType = type;
46: this.carSize = "Small";
47: }
48:
49: NewCar(int type,String size)//建構子3 overloading
50: {
51: System.out.println("in NewCar(int type , String size)");
52: setCarType(type);
53: this.setCarSize(size);
54: }
55:
56: //成員函式
57: int getCarType()//注意:成員函式(方法)要設定回傳值
58: {
59: return carType;
60: }
61:
62: void setCarType(int type)
63: {
64: carType = type;
65: }
66:
67: void setCarSize(String size)
68: {
69: this.carSize = size;
70: }
71:
72: String getCarSize()
73: {
74: return this.carSize;
75: }
76:
77: void setNum(int...is)//參數列表(等於傳陣列)
78: {
79: for(int i : is)//使用 for-each
80: {
81: System.out.println(i);//0 1 2 3
82: }
83: }
84:
85: void showCarInfo()
86: {
87: System.out.println(carType);
88: System.out.println(carSize);
89: }
90:
91: }
92:
93: class SuperCar extends NewCar// SuperCar 繼承 NewCar
94: {
95: final int carSpeed = 500;//final 必須初始話或在建構子初始化
96: final boolean carFly;
97:
98: SuperCar()
99: {
100: super.carType =1;//取得父類別的carType
101: carFly = true;//final 也可以放在 建構子初始化
102: System.out.println("in SuperCar()");
103: this.showCarInfo();//呼叫自己的showCarInfo
104: }
105:
106: SuperCar(int type,String size)
107: {
108: super(type,size);//使用super或this呼叫建構子必須放在第一行
109: carFly = true;
110: }
111:
112: void showCarInfo()//overriding 改寫父類別的
113: {
114: super.showCarInfo();//呼叫父類別的showCarInfo
115: System.out.println(carSpeed);
116: System.out.println(carFly);
117: }
118:
119: //SuperCar is-a NewCar
120: //SuperCar has-a showCarInfo
121: }