物件導向的三大特型:封裝、繼承、多型。
不過或許我們應該先來講類別和物件的關係。
在物件導向的世界裡,很多東西都是由一個一個物件構成的。舉凡一些感覺很「具體」的東西都可以是物件,例如房子、Xperia Z5、杯子、橡皮擦、哈士奇、Noob……等等,而類別通常是一些比較籠統的東西,例如車、人、飛機之類的。
雖然也沒有規定那些東西一定是物件或類別,不過通常我們會在類別裡定義它的特性,並透過這個類別來建立一個物件。
類別
類別比較算是一個範本,裡面定義好該有的屬性和方法,其中方法又大概可以分為一般的方法、類別方法和建構子。例如我們可以定義一個學生類別,裏面包含了name、score屬性,以及getName()方法、setScore()方法。
物件
物件則是實體的東西,由定義好的類別來建立一個物件。例如 Peter 是一個學生、Amy 是一個學生。
那麼 Peter 就會擁有 Student 類別的屬性和方法,所以 Peter 會有 name、score 屬性、getName()、setScore() 方法,Amy 也會有自己的 name、score 屬性、getName()、setScore()方法。- class Student{
- public String name;
- public int score;
-
- Student(String n, int s){
- name = n;
- score = s;
- }
-
- public void getName(){
- return name;
- }
-
- public void setScore(int s){
- score = s;
- }
-
- public static void helloWorld(){
- System.out.println("Hello, World!");
- }
- }
-
- public class class_test{
- public static void main(String[] agrs){
- Student Peter = new Student("Peter", 88);
- Student Amy = new Student("Amy", 85);
-
- Student.hellowWorld();
- }
- }
複製代碼 |