iT邦幫忙

1

[Java] static 關鍵字

  • 分享至 

  • twitterImage
  •  

閱讀時間: 5分鐘

在Java中,static關鍵字的主要作用是用於記憶體管理。
可以將static關鍵字用在variables, methods, blocks和nested classes。

1, Variable (可以稱為class variable)
Static variable 可以用作代表會多次使用的物件(Object),例如 產品名稱、地方名稱、學校名稱等等。
當class被讀取時,static variable會馬上被分配記憶體在class area內。
所以static variable的好處就是可以提升記憶體使用效率。

例子: 沒有static variable下,每個物件都需要記憶體儲存college = "ITSchool"。
假如有1000個學生,就需要重複創建1000個college = "ITSchool"。

class Student{  
     int rollno;  
     String name;  
     String college="ITSchool";  
}  

例子: 有static variable下,即使有1000個學生,都不用重複創建1000個college = "ITSchool"。
節省了大量記憶體。

class Student{  
   int rollno;//instance variable  
   String name;  
   static String college ="ITSchool"; //static variable  
   //constructor  
   Student(int r, String n){  
   rollno = r;  
   name = n;  
   }  
   //method to display the values  
   void display (){System.out.println(rollno+" "+name+" "+college);}  
}  

public class TestStaticVariable1{  
 public static void main(String args[]){  
 Student s1 = new Student(1,"Tom");  
 Student s2 = new Student(2,"Mary");  
s1.display();  
  s2.display();  
 }  
}  

2, Method (可以稱為class method)
Static method 屬於class,,而不是屬於Object。
Static method 可以直接存取static 資料及改變它們的值。

例子:

class Student{  
     int rollno;  
     String name;  
     static String college = "ITSchool";  
     //static method 改變 static variable 的值 
     static void change(){  
     college = "AITSchool";  
     }  
     //constructor 
     Student(int r, String n){  
     rollno = r;  
     name = n;  
     }  
     
     void display(){System.out.println(rollno+" "+name+" "+college);}  
}  

public class TestStaticMethod{  
    public static void main(String args[]){  
    Student.change(); 
    
    Student s1 = new Student(1,"Tom");  
    Student s2 = new Student(2,"Mary");  
    Student s3 = new Student(3,"Ben");  
    
    s1.display();  
    s2.display();  
    s3.display();  
    }  
}  

3, Block
可以用作建立static資料。
可以在main method前被執行。

例子:

class A2{  
  static{System.out.println("static block is invoked");}  
  public static void main(String args[]){  
   System.out.println("Hello main");  
  }  
}  

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言