- public class ch31 //類別
- {
- public static void main(String args[]) //主方法
- {
- Car bus=new Car(); //於Car類別下, 宣告物件並產生時體, 分別命名為bus, truck, taxi
- Car truck=new Car();
- Car taxi=new Car();
-
- bus.name="公車"; //定義該物件的屬性
- bus.wheel=6;
- bus.person=40;
- truck.name="卡車";
- truck.wheel=8;
- truck.person=3;
- taxi.name="計程車";
- taxi.wheel=4;
- taxi.person=5;
- System.out.println(bus.name+"有"+bus.wheel+"個輪子,可載"+bus.person+"人");
- System.out.println(truck.name+"有"+truck.wheel+"個輪子,可載"+truck.person+"人");
- System.out.println(taxi.name+"有"+taxi.wheel+"個輪子,可載"+taxi.person+"人");
- }
- }
- class Car //定義Car類別, 宣告該類別中的三個變數(屬性)
- {
- int wheel;
- int person;
- String name;
- }
複製代碼 |