1. 程式人生 > 實用技巧 >java8 ->map遍歷

java8 ->map遍歷

static關鍵字

靜態屬性

若類中有靜態變數,可直接使用類名訪問:

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);//直接使用類名訪問靜態變數age
        //System.out.println(Student.score);//會報錯
        System.out.println(s1.age);
        System.out.println(s1.score);
    }
}

靜態變數對於這個類而言,在記憶體中只有一個,能被當前類所有例項共享

靜態方法

非靜態方法可以直接訪問當前類中的靜態方法

靜態方法可以呼叫靜態方法但不能呼叫非靜態方法

public class Student {
    private static int age;//靜態變數
    private double score;//非靜態變數

    public void run(){

    }
    public static void go(){

    }
    public static void main(String[] args) {

        go();
        Student.go();
        //run();//報錯
        //呼叫方式
        Student student = new Student(); 
        student.run();
    }
}

靜態程式碼塊

public class Person {
    {
        //匿名程式碼塊(一般不建議)
    }
    
    static{
        //靜態程式碼塊(載入一些初始化的資料)
    }
}
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();
    }
}

輸出結果:

  • 匿名程式碼塊:

    建立物件時自動建立,在構造器之前

    可以用於賦初始值

  • 靜態程式碼塊:

    類一載入就執行,永久只執行一次

    public static void main(String[] args) {
        Person person = new Person();
        System.out.println("-----------------------");
        Person person1 = new Person();
    }

輸出結果:

靜態匯入包

平時:

public class Test {

    public static void main(String[] args) {
        System.out.println(Math.random());
    }
}

採用靜態匯入包:

//靜態匯入包
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);
    }
}