阅读时间: 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"); } }