類別的封裝路徑
package 代表類別所在程式碼根目錄中的相對路徑類別的存取層級
- public 所有類別均能存取使用
- protected 相同路徑下的類別或衍生類別才能存取使用
- private 只有該類別中才能存取使用
- 空白 未定義時預設為 protected
類別的修飾子
- static 將被修飾的物件宣告為類別物件,該類別中都可使用
- final 將被修飾的物件宣告為常數,也就是不可更改其屬性
建立類別的方式
1 2 3 4 5 6 7 8 9 10 11 12 | package [封裝路徑]; [存取層級] [修飾子] class [類別名稱] { [資料型態] [變數名稱]; [資料型態 ] [方法名稱]([參數]){ 程式敘述... return [資料型態值]; } } |
建立車輛類別
在專案中新建1個類別,類別名稱為Car1 2 3 4 5 6 7 | public class Car { int speed; //速度 int Weight; //重量 int size; //尺寸 } |
在主程式 main class中建構車輛類別
1 2 3 4 5 6 7 8 9 10 11 12 | public static void main(String[] args) throws IOException { Car car= new Car(); car.speed= 100 ; car.size= 3 * 2 ; car.Weight= 1000 ; System.out.println(car.speed); System.out.println(car.size); System.out.println(car.Weight); } |
以建構子的方式建立車輛類別
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class Car { int speed; //速度 int Weight; //重量 int size; //尺寸 public Car( int speed, int weight, int size){ this .speed=speed; this .Weight=weight; this .size=size; } } |
在主程式 main class中以建構子建立車輛類別
1 2 3 4 5 6 7 8 | public static void main(String[] args) throws IOException { Car car= new Car( 100 , 1000 , 2 * 3 ); System.out.println(car.speed); System.out.println(car.size); System.out.println(car.Weight); } |
以呼叫方法建立車輛類別
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | public class Car { int speed; //速度 int Weight; //重量 int size; //尺寸 public int getSpeed() { return speed; } public void setSpeed( int speed) { this .speed = speed; } public int getWeight() { return Weight; } public void setWeight( int weight) { Weight = weight; } public int getSize() { return size; } public void setSize( int size) { this .size = size; } } |
在主程式 main class中以呼叫方法建立車輛類別
1 2 3 4 5 6 7 8 9 10 11 12 | public static void main(String[] args) throws IOException { Car car= new Car(); car.setSize( 3 * 2 ); car.setSpeed( 100 ); car.setWeight( 1000 ); System.out.println(car.speed); System.out.println(car.size); System.out.println(car.Weight); } |
綜合練習
設計1個汽車類別,分別製造3輛汽車。在主程式中計算出3輛車行駛450公里所需的時間
此練習為類別實作應用,結果值以小時為單位小數點無需換算為分鐘
沒有留言:
張貼留言