JAVA Static
static 靜態
作用對象
可用來修飾 (類別的屬性、方法或子類別),不能用 static 修飾最上層 Class
定義
靜態的意思是,在程式載入記憶體的時候,跟著程式一起在記憶體中佔有空間,而不是主程式開始執行後才跟記憶體要空間。
static 可以想像成程式執行時已經載入到記憶體中,有點類似於全域的概念,Java 中沒有全域性變數的概念。但可以透過 static 實現此目的,可以將變數宣告為靜態並將其用作全域性變數。
範例 1
如果物件內定義 static 屬性,就可以使用類名稱訪問靜態變數,不需要建立一個物件來呼叫靜態變數。
| 12
 3
 4
 
 | class Student{static int id;
 static String name;
 }
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 
 | public class StaticTesting{public static void main(String[] args) {
 Student.id = 1;
 Student.name = "Sean";
 int StudentId = Student.id;
 String StudentName = Student.name;
 System.out.println("Id: "+StudentId);
 System.out.println("Name: "+StudentName);
 }
 }
 
 | 
Output:
範例 2
static 也可以同時用在類別方法中,可以讓有被注入這個類別的程式內都可以使用,類似於使得類別內的變數擁有全域的特性
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 
 | public class GlobalVarTest {static String Global;
 
 
 public static void setGlobal(String s) {
 Global = s;
 }
 
 public static String getGlobal() {
 return Global;
 }
 
 }
 
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 
 | pubic class TestGlobal1 {
 public String print(){
 String a = "hi";
 Global.setGlobal(a)
 System.out.println("TestGlobal1 set Global: " + GlobalVarTest.getGlobal());
 }
 }
 
 pubic class TestGlobal2 {
 
 public String print(){
 String b = "123";
 Global.setGlobal(b)
 System.out.println("TestGlobal2 set Global: " + GlobalVarTest.getGlobal());
 }
 }
 
 
 | 
Output:
| 12
 
 | TestGlobal1 set Global: hiTestGlobal2 set Global: 123
 
 |