###### tags: `Java 學習筆記` # Java 學習筆記 - 8-1: 物件導向: 類別 Class ## 類別 Java 是一個全物件導向程式語言(Objected-Oriented Program Language, OOPL),所有東西都會被放在類別裡,類別就像模板,通過類別 new 出來的東西就叫做物件(會存在 heap 中),類別也是一種參考資料型態 類別會描述物件,用以下兩種方式: * 屬性(Property): 類別中的屬性 * 方法(Method): 類別中的功能 類別的命名一定是大寫開頭(巴斯塔命名法) package 命名為全小寫不做區隔 ## 類別結構 ```java= [封裝等級][修飾字] class 類別名稱 [extends 父類別][implements 介面] { [封裝等級][修飾字] 資料型態 field名稱1; [封裝等級][修飾字] 資料型態 field名稱2; : : [封裝等級][修飾字] 回傳資料型態 method名稱1(參數宣告串) { method的內容 } [封裝等級][修飾字] 回傳資料型態 method名稱1(參數宣告串) { method的內容 } : : } ``` ### 封裝等級 會用在類別和方法,類別中可以對 fields & methods 定義四種封裝等級: 1. public: 最常用到,公用等級資料型態,他人可以使用 2. private: 最常用到,私用等級資料型態,他人不可使用,通常類別內的屬性都會用 private 以避免他人直接存取 4. protected: 保護性等級資料型態 5. 空白: package等級(Default) 同一個 package 底下的 class 可以存取 方法外的屬性也會有封裝等級,方法內的屬性沒有封裝等級 ```java= public class Shape { public int a; public void test() { int a = 3; // 裡面的 a this.a = 5; // 外面的 a, this 代表當前操作的物件本身 } } ``` ```java= public class Main { public static void main(String[] args) { Shape s1 = new Shape(); // s1 object // 實體 instance Shape s2 = new Shape(); s1.test(); s2.test(); // 會在 heap 中各創造出兩個 Shape System.out.println(s1.a); } } ``` ### 實體 instance 指定類別的物件就是實體 Shape s1 = new Shape(); 裡面的 s1 就是實體 ## 物件導向的封裝性 允許間接存取 屬性的修改器(mutator/setter)和存取器(accessor/getter) ## 拿取資訊 只要在同樣的類別之中,就可以拿該變數內所有屬性 ## this 使用 this 拿取在類別中的變數而非外面傳入的資訊 this. 代表當前操作的物件 ## 建構子 創建空間的時候就賦予裡面的屬性初始值,即給予初始值 建構子也是一種方法,要寫在該類別裡面 ```java= public class Sss { private String name; private int price; public Sss(String name) { this.name = name; } public Sss(String name, int price) { // 建構子的多載 this.name = name; this.price = price; } } ``` 建構子的名稱和該類別完全相同,可寫多載建構子,如果向上面寫法,只寫一個 name 也可以,就只會跑上面 ## 類別範例: Rectangle 包含屬性: int wigth, int height 必要屬性: width & height 且都必須大於 0, 當值 <= 0 時強制設定為 1 包含方法: 取得面積 getArea() 取得周長 getPetrimeter() 比較兩長方形面積大小 compare() ```java= public class Rectangle { private int width; private int height; public void setWidth(int width) { // setter if(width <= 0) { this.width = 1; return; } this.width = width; } public int getWidth() { return this.width; } public void setHeight(int height) { // setter if(height <= 0) { this.height = 1; return; } this.height = height; } public int getHeight() { // getter return this.height; } public int getArea() { // getter return this.getWidth() * this.getHeight(); } public int getPetrimeter() { return (this.getWidth() + this.getHeight()) * 2; } public int compare(Rectangle rect) { return this.getArea() - rect.getArea(); } public Rectangle(int width, int height) { this.setWidth(width); this.setHeight(height); } } ```