JAVA是物件導向的語言,物件導向最重要的就是他有class(類別)的概念。(動態網頁程式 Chap.2)
【類別】就像藍圖,而【物件】就是由藍圖製作出來的有功能性的東西,【物件】又有【屬性】和【方法】
(2021.09.28補充)
類別內宣告的變數就是【屬性】,創建的函式就是【方法】
JAVA必須由【類別】為單位,一個檔案可以有許多類別,但只可以有一個宣告成公用(public)。
存檔的名稱必須和宣告為公用的類別名一致
宣告為public的類別為【主程式類別】,必須含有程式最初執行點 main() 方法
類別的建立
修飾語 class 類別名稱
例:public class MainClass{
}
物件的建立
【類別】建立完後,再來要建構出【物件】,不然程式沒有實際的東西可以執行
【物件】包含資料和函數,也就是【屬性】和【方法】
要將【類別】建構出【物件】的語法為
類別 物件名稱 = new 物件建構子;
物件建構子:
1.是一種方法
2.必須和類別名稱相同
3.不可以指定回傳值
(2021.09.28補充)
new是把類別實體化,會在heap記憶體中,分配出空間給這個物件
例如:
Student st = new Stuedent();
st就是Student類別的【實體】
舉例來說~
ex1: ObjCreate .java
ex2: MainClass .java
ex1和ex2的差別在於:
ex2加上了MainClass的建構子
(2021.09.28補充)
在類別中,可以創建建構子,在使用者創建這個類別的物件時,就設定好參數
類別中宣告的變數,需要設置setter和getter來設定和回傳值,目前學到的是這麼說
但網路上似乎有另一套說法,認為setter和getter並不是完完全全的必要,必須看需求來調整
https://www.ithome.com.tw/voice/98804
關鍵字this表示的是【使用當前】類別的變數
https://www.1ju.org/java/this-keyword
以下是Rectangle的類別範例
設定創建此物件時,須設定好長方形的長和寬
此類別下有【方法】可以取得周長、面積、和比較兩個長方形的面積
public class Rectangle { //屬性 private int width; private int height; //建構子 public Rectangle(int width, int height) { setWidth(width); setHeight(height); } private void setWidth(int width) { if(width<=0){ this.width = 1; }else { this.width = width; } } private void setHeight(int height) { if(height<=0){ this.height = 1; }else { this.height = height; } } private int getWidth(int width) { return this.width = width; } private int getHeight(int height) { return this.height = height; } //方法 public int getArea() { return this.height*this.width; } public int getPerimeter(){ return (this.height+this.width)*2; } public int areaCompared(Rectangle r2){ int r2Area = r2.getArea(); return this.getArea()-r2Area; } }
java命名規範
類別:使用大寫開頭的駝峰命名,例如:MainClass
變數命名:使用小寫開頭的駝峰命名,例如:countNum
常數(final建構):全大寫,例如:PI
