顯示具有 OO 標籤的文章。 顯示所有文章
顯示具有 OO 標籤的文章。 顯示所有文章

2008年10月14日 星期二

static 的使用時機

首先大致了解一下 static 這個修飾字,及使用規則。

static 是屬於類別層級的修飾字,在記憶體裡面只存有一份,不論我們 new 了幾個物件,該成員或函示始終指向同一個記憶體位置。而 static 成員只能被 static 成員呼叫或存取。

在使用的時機方面,static 是在任何物件運作之前就會被呼叫的,因此我們也常常使用
main method 來作測試,再來就是常見的公用 method,類似 Utilites,與不會改變的常數等等。

下列有個例子舉的很好,可以拿來說明:

public class StaticModifier
{
int counter1 = 0;
static int counter2 = 0;

public void Increase(String s)
{
counter1++;
counter2++;
System.out.print(s + "'s counter1 = " + counter1);
System.out.println("; counter2(static) = " + counter2);
}

public static void main(String argv[])
{
StaticModifier sta1 = new StaticModifier();
StaticModifier sta2 = new StaticModifier();

sta1.Increase("sta1");
sta1.Increase("sta1");
sta2.Increase("sta2");
}
}
程式輸出為:
sta1's counter1 = 1; counter2(static) = 1
sta1's counter1 = 2; counter2(static) = 2
sta2's counter1 = 1; counter2(static) = 3
Reference:
http://www.javaworld.com.tw/jute/