- public class Ch01 {
- public static void main(String[] args) {
- Car bus=new Car("公車",6,40);
- Car truck=new Car("卡車",8,3);
- Car taxi=new Car("計程車",4,5);
-
- System.out.println(bus.name+"有"+bus.wheel+"個輪子,可載"+bus.load+"人.");
- System.out.println(truck.name+"有"+truck.wheel+"個輪子,可載"+truck.load+"人.");
- System.out.println(taxi.name+"有"+taxi.wheel+"個輪子,可載"+taxi.load+"人.");
- class Car //自訂類別
- {
- String name; //宣告該類別擁有哪些屬性
- int wheel;
- int load;
- Car() //沒帶任何參數的建構子
- {
- }
- Car(String name, int wheel, int load) //帶三個參數的建構子
- {
- this.name=name;
- this.wheel=wheel;
- this.load=load;
- }
- Car(String n, int w) //帶兩個參數的建構子
- {
- name=n;
- wheel=w;
- }
- //方法 (尚未定義)
- }
- }
- }
複製代碼 |