Java面向對象系列(12)- Static關鍵字講解
- 2021 年 9 月 24 日
- 筆記
- Java面向對象, 測試開發 - Java
場景一:靜態變數
package oop.demo07; public class Student { private static int age;//靜態的變數 一般多執行緒用的比較多 private double score;//非靜態變數 public static void main(String[] args) { Student s1 = new Student(); System.out.println(Student.age); //static靜態變數,可以通過類直接調用 System.out.println(s1.age); System.out.println(s1.score); } }
場景二:靜態方法
package oop.demo07; public class Student { public void run(){ System.out.println("Run"); go(); //可以直接調用靜態方法 } public static void go(){ System.out.println("go"); } public static void main(String[] args) { Student.go(); //靜態方法可以通過類直接調用 go(); //同時靜態方法還支援直接調用 new Student().run();//非靜態方法,需要先new進行實例,才能調用 } }
Static修飾的含義隸屬於類,而不是對象,是一個公共的存儲記憶體的空間
場景三:程式碼塊
package oop.demo07; public class Student { /* { //程式碼塊(匿名程式碼塊) 創建對象的時候就創建了匿名程式碼塊,而且在構造器之前 } static { //靜態程式碼塊 常用於載入一些初始化的數據 類一載入就執行,永久只執行一次 } */ //第二個執行 { System.out.println("匿名程式碼塊"); } //第一個執行 static { System.out.println("靜態程式碼塊"); } //第三個執行 public Student() { System.out.println("構造器(構造方法)"); } public static void main(String[] args) { Student student = new Student(); } }
Static程式碼塊只執行一次,匿名程式碼塊和構造器new一次,執行一次
場景四:靜態導入包
常規
package oop.demo07; public class Student { public static void main(String[] args) { System.out.println(Math.random()); System.out.println(Math.PI); } }
靜態導入包,調用方法更簡潔
package oop.demo07; //靜態導入包 import static java.lang.Math.random; import static java.lang.Math.PI; public class Student { public static void main(String[] args) { System.out.println(random()); System.out.println(PI); } }