本帖最後由 tonyh 於 2015-1-24 17:04 編輯
定義帶不同參數數量的建構子- public class ch58 //主類別
- {
- public static void main(String args[]) //主方法
- {
- Car bus=new Car("公車",6,40); //在Car類別下,生成一個名為bus的實體物件
- //Car truck=new Car("卡車");
- Car truck=new Car(8,3);
- //Car truck=new Car();
- truck.name="卡車";
- Car taxi=new Car("計程車",4,5);
- System.out.println(bus.name+"有"+bus.wheel+"個輪子,可載"+bus.carry+"人.");
- System.out.println(truck.name+"有"+truck.wheel+"個輪子,可載"+truck.carry+"人.");
- System.out.println(taxi.name+"有"+taxi.wheel+"個輪子,可載"+taxi.carry+"人.");
- }
- }
- class Car //定義Car類別
- {
- String name;
- int wheel;
- int carry;
- Car() //定義不帶任何參數的建構子
- {
- }
- Car(String name) //定義只帶一個參數的建構子
- {
- this.name=name;
- }
- Car(int wheel, int carry) //定義只帶二個參數的建構子
- {
- this.wheel=wheel;
- this.carry=carry;
- }
- Car(String name, int wheel, int carry) //定義帶三個參數的建構子
- {
- this.name=name;
- this.wheel=wheel;
- this.carry=carry;
- }
- }
複製代碼 |