static修飾符
阿新 • • 發佈:2022-03-30
靜態變數和靜態方法
public class Student { private static int age;//靜態的變數 private double score;//非靜態變數 //非靜態方法 public void run(){ } //靜態方法 public static void go(){ } public static void main(String[] args) { Student s1 = new Student(); System.out.println(Student.age);//System.out.println(Student.score);//score非靜態不能呼叫 System.out.println(s1.score); System.out.println(s1.age); //靜態方法與非靜態方法呼叫的區別 go(); s1.run(); } }
靜態程式碼塊
執行順序:靜態程式碼塊>匿名程式碼塊>構造方法
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(); } }
靜態匯入包
package oop.constructor.demo1; //靜態匯入包 import static java.lang.Math.random; public class Test { public static void main(String[] args) { //System.out.println(Math.random());非靜態匯入包呼叫方法 System.out.println(random()); } }