2016/4/24

定義class:Java為例



配合這張圖class概念會很好懂



class就像設計圖一樣,它會有顏色和尺寸,這些是他的成員

你會根據設計圖製作實際的衣服,也就是實體的物件Object,每個衣服你會給它一個這款是衣服的名牌c1 c2 c3

衣服的程式怎麼寫?

class Clothes {
    String color;
    char size;
}

定義一個叫Clothes的class

用Clothes class製作實體的衣服:

new Clothes();  這叫做創造一個新的物件

給這物件一個名稱:

Clothes c1;

Java中c1叫參考名稱(Reference name)、參考變數(Reference variable)

將c1綁定到新建的物件上:

Clothes c1 = new Clothes();    這就是我們寫程式時,常看到的東西了,現在懂它的意思了吧

而物件導向有個東西叫實例(Instance),在Java中它與物件(Object)幾乎同等意義

package cc.openhome;
class Clothes {
    String color;
    char size;
}
public class Field {
    public static void main(String[] args) {
        Clothes sun = new Clothes();
        Clothes spring = new Clothes();

        sun.color = "red";
        sun.size = 'S';        
        spring.color = "green";
        spring.size = 'M';
        
        System.out.printf("sun (%s, %c)%n", sun.color, sun.size);
        System.out.printf("spring (%s, %c)%n", spring.color, spring.size);
    }
}

以前每次寫到Clothes sun = new Clothes();這東西的時候

總是不知道這到底是什麼意思,只知道有些功能要用一定要這行

現在知道了,它背後有個叫class的東西

class是虛的,而new出來後,我們才可以用它,變實體

而Clothes class有兩個值域(Field)成員,color  size

每次建立新Clothes 實例,都會擁有這兩個值

回頭看整份程式碼,此有兩類別,一非公開的Clothes  二是公開的public Field,

所以此份程式碼檔名必為Field.java,而一份原始碼中可有多個類別定義但公開的只能有一個類別

執行結果如下:

sun (red, S)
spring (green, M)

剛的範例中,為個別物件指定資料成員值,

那你想要在物件建立時,進行某初始流程,直接指定資料成員值,可用建構式(Constructor),它是與類別名稱同名的方法method

package cc.openhome;
class Clothes2 {
    String color;
    char size;
    Clothes2(String color, char size) {
        this.color = color;
        this.size = size;
    }
}
public class Field2 {
    public static void main(String[] args) {
        Clothes2 sun = new Clothes2("red", 'S');
        Clothes2 spring = new Clothes2("green", 'M');
        
        System.out.printf("sun (%s, %c)%n", sun.color, sun.size);
        System.out.printf("spring (%s, %c)%n", spring.color, spring.size);
    }
}

又看到了嗎?Clothes2 sun = new Clothes2("red", 'S');

是不是平時寫程式也會有這種格式的語法出現呢?現在懂了吧



還有,如果class.java檔與main.java檔都在同一個Package下

就不用import

如果兩個java都在各別的Package,就需要import,這樣main.java才能存取class的物件



您還可以看:訊息傳遞(Message Passing)和函數呼叫(Function Call)的不同點
參考:
程鼎元(Ding-Yuan Cheng)-074-Java參考值呼叫 (Call by Reference)
程鼎元(Ding-Yuan Cheng)-075-Java傳值呼叫(Call By Value)
ava物件導向程式設計wiki 董少桓編著

沒有留言:

張貼留言