java 中 static關鍵字
阿新 • • 發佈:2021-08-03
1,新建Person類
package oop.demo08; /* 靜態程式碼塊 */ //public final class Person { ------定義 final 之後 不能被繼承 public class Person { { // 程式碼塊(匿名) // 跟物件同時產生 --------賦一些初始值 System.out.println("匿名程式碼塊"); } static { //類載入執行 (永久 只執行一次) //靜態程式碼塊 System.out.println("靜態程式碼塊"); } public Person() { System.out.println("無參構造方法"); } public static void main(String[] args) { Person person = new Person(); System.out.println("=================="); Person person2 = new Person(); } /* 依次輸出的順序是: 靜態程式碼塊 匿名程式碼塊 無參構造方法 ================== 匿名程式碼塊 無參構造方法 */ }
執行結果
2,新建Student類
package oop.demo08; //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);//0 System.out.println(s1.age);//0 System.out.println(s1.score);//0.0 // 通過物件點方法呼叫 new Student().run(); Student.go(); go(); } }
執行結果
3,新建Test類
package oop.demo08;
//靜態匯入包
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);//3.141592653589793
}
}