1. 程式人生 > 其它 >static& final關鍵字詳解\程式碼塊\靜態匯入包

static& final關鍵字詳解\程式碼塊\靜態匯入包

static& final關鍵字詳解\程式碼塊\靜態匯入包

package zaiyang.oop.demo07;

public class Student  {
    //static
    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(s1.age);//靜態屬性
        System.out.println(s1.score);//非靜態屬性,不能使用類名訪問

        new Student().run();//非靜態方法必須new類才能呼叫
        Student.go();//靜態方法不用new就能呼叫,在當前類,非靜態方法可以呼叫靜態方法,靜態方法可以呼叫靜態方法。
        // 因為靜態方法是和類一起載入的所以能呼叫,非靜態方法沒有載入所以無法呼叫。
    }
}
package zaiyang.oop.demo07;
//final為最終的,被final修飾的類無法被繼承
public  final 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 person1 = new Person();
    }
}
/*
        靜態程式碼塊
        匿名程式碼塊
        構造器方法
        =================================
        匿名程式碼塊
        構造器方法

 */
package zaiyang.oop.demo07;

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