Static詳解
阿新 • • 發佈:2020-07-13
Static詳解
//static : 和類一起載入的 public class Student { private static int age; //靜態的變數 多執行緒! private double score; //非靜態的變數 public void run(){//非靜態方法可以呼叫所以靜態的方法 go(); } public static void go(){ } public static void main(String[] args) { // Student s1 = new Student(); // System.out.println(Student.age); //假設是靜態變數,建議使用類來訪問 // //System.out.println(Student.score); // System.out.println(s1.age); // System.out.println(s1.score); //static可以擴大使用範圍 new Student().run(); go(); } }
測試看輸出結果
public class Person { //2: 賦初始值 { System.out.println("匿名程式碼塊"); //程式碼塊(匿名程式碼塊) 建立這個物件自己的就建立了(在構造器之前) } //1 static { System.out.println("靜態程式碼塊"); //靜態程式碼塊(載入一些初始的東西),類載入就執行了,永久只執行一次 } //3 public Person(){ System.out.println("構造方法"); } public static void main(String[] args) { Person person1 = new Person(); System.out.println("============"); Person person2 = new Person(); } }
java靜態匯入包
//靜態匯入包
import static java.lang.Math.random;
import static java.lang.Math.PI;
public class Test {
public static void main(String[] args) {
System.out.println(random());
System.out.println(PI);
}
}