Day11_static、匿名代码块、静态导入包

static

变量和方法

1.静态属性可以直接通过类调用

2.非静态属性不可以通过类调用

3.静态方法直接通过类名调用

4.非静态方法需通过实例调用

//static
public class Student {
    private static int age;//静态的变量 多线程用到
    private double score;//非静态变量

    public void run(){

    }

    public static void go(){
        System.out.println("gogogo");
    }

    public static void main(String[] args) {
        Student s1 = new Student();
        //静态属性可以直接通过类调用
        System.out.println(Student.age);
        //非静态属性不可以通过类调用
//        Student.score;
        //非静态属性只能通过实例去调用
        System.out.println(s1.score);
        System.out.println(s1.age);
        //静态方法直接通过类名调用
        Student.go();
        //在本类之内可通过名字直接调用
        go();
        //非静态方法需通过实例调用
        s1.run();
    }
}

匿名代码块、静态代码块、构造器加载顺序

public class Person {
    //1(静态代码块只执行一次)

    static {
        //静态代码块
        System.out.println("静态代码块");
    }
    //2(匿名代码块可以用来赋初始值)

    {
        //代码块(匿名代码块)
        System.out.println("匿名代码块");
    }
    //3

    public Person(){
        System.out.println("构造方法");
    }

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

static只执行一次

静态导入包

//静态导入包
import static java.lang.Math.random;

public class Test {
    public static void main(String[] args) {
        System.out.println(random());
        //上面这句等于
        System.out.println(Math.random());
    }
}
posted @ 2021-02-17 14:27  Bobool  阅读(67)  评论(0)    收藏  举报