返回列表 發帖

物件導向-封裝

物件導向的三大特型:封裝、繼承、多型。

不過或許我們應該先來講類別和物件的關係。


在物件導向的世界裡,很多東西都是由一個一個物件構成的。舉凡一些感覺很「具體」的東西都可以是物件,例如房子、Xperia Z5、杯子、橡皮擦、哈士奇、Noob……等等,而類別通常是一些比較籠統的東西,例如車、人、飛機之類的。

雖然也沒有規定那些東西一定是物件或類別,不過通常我們會在類別裡定義它的特性,並透過這個類別來建立一個物件。

類別
類別比較算是一個範本,裡面定義好該有的屬性和方法,其中方法又大概可以分為一般的方法、類別方法和建構子。例如我們可以定義一個學生類別,裏面包含了name、score屬性,以及getName()方法、setScore()方法。

物件
物件則是實體的東西,由定義好的類別來建立一個物件。例如 Peter 是一個學生、Amy 是一個學生。

那麼 Peter 就會擁有 Student 類別的屬性和方法,所以 Peter 會有 name、score 屬性、getName()、setScore() 方法,Amy 也會有自己的 name、score 屬性、getName()、setScore()方法。
  1. class Student{
  2.         public String name;
  3.         public int score;
  4.        
  5.         Student(String n, int s){
  6.                 name = n;
  7.                 score = s;
  8.         }
  9.        
  10.         public void getName(){
  11.                 return name;
  12.         }
  13.        
  14.         public void setScore(int s){
  15.                 score = s;
  16.         }

  17.         public static void helloWorld(){
  18.                 System.out.println("Hello, World!");
  19.         }
  20. }

  21. public class class_test{
  22.         public static void main(String[] agrs){
  23.                 Student Peter = new Student("Peter", 88);                       
  24.                 Student Amy = new Student("Amy", 85);

  25.                 Student.hellowWorld();
  26.         }
  27. }
複製代碼

返回列表