[Java] Class 的 Static 和 Instance 元素

以Instance來說,Class只是一個模型,在new的時候複製一份至每個物件的記憶體空間中,因此每個物件中的元素互相不共用

而Static則是將元素限定於Class本身的記憶體,new的時候是將元素本身的參照存至物件記憶體中,而非複製,此外也能直接透過Class本身去存取該元素

Instance範例

public class test
{
    public static void main(String args[])
    {
        Foo bar; // 產生一個名為bar的Foo空物件
        bar = new Foo(); // 將Foo複製到物件bar
        bar.setFoobar(35); // 設定bar物件中的foobar變數
        bar.getFoobar(); // 回傳bar物件中的foobar變數
    }
}

class Foo
{
    private int foobar;

    void setFoobar(int foobar)
    {
        this.foobar = foobar; // 設定當前物件(this)的foobar變數
    }

    int getFoobar()
    {
        return this.foobar; // 回傳當前物件(this)的foobar變數
    }
}

對Instance來說Class只是一個模型,所以this是指當前物件,在new給物件之前,這並沒有指向任何東西

Static範例

public class test
{
    public static void main(String args[])
    {
        // 透過物件存取,不建議這樣使用
        Foo bar; // 建立名為bar的Foo物件
        bar = new Foo(); // 將Foo複製到物件bar
        bar.setFoobar(40); // 透過物件bar設定foobar變數
        bar.getFoobar(); // 透過物件bar取回foobar變數

        // 直接存取
        Foo.setFoobar(35); // 透過Class本身的方法去設定foobar變數
        Foo.getFoobar(); // 透過Class本身的方法回傳foobar變數
    }
}

class Foo
{
    private static int foobar;

    static void setFoobar(int foobar)
    {
        Foo.foobar = foobar; // 將Class的foobar設為傳入變數foobar
    }

    static int getFoobar()
    {
        return Foo.foobar; // 回傳Class的foobar變數
    }
}

留言

粗體斜體刪除線連結引用圖片程式碼

注意:您的電子信箱將不會被公開,且網站連結不會被搜尋引擎採計

{124} {123} {122} {121} {120} {119} {118} {117} {116} {115} {114} {113} {112} {111} {100} {025} {024} {023} {022} {021} {020} {019} {018} {017} {016} {015} {014} {013} {012} {011} {010} {009} {008} {007} {006} {005} {004} {003} {002} {001}