static关键字相关内容

  • 静态变量(static)与非静态变量,静态方法(static)与非静态方法
//static
public class Student {

    private static int age; //静态的变量(静态属性)
    private double score;   //非静态的变量

    public void run(){  //非静态方法
    }
    public static void go(){    //静态方法
    }

    public static void main(String[] args) {
        //run();//编译错误,非静态方法不能直接使用
        new Student().run();//必须将对象实例化后再调用非静态方法
        Student student = new Student();//两种不同的实例化方式
        student.run();

        go();//静态方法可直接使用
        Student.go();
    }
    /*public static void main(String[] args) {
        Student s1 = new Student();

        System.out.println(Student.age);//静态变量可直接使用类名访问,静态变量又称为类变量
        //System.out.println(Student.score);//编译错误,非静态字段不能使用类名访问
        System.out.println(s1.age);
        System.out.println(s1.score);
    }*/
}

  • 类中匿名代码块,静态代码块(加载类的同时加载,只执行一次)及构造方法执行顺序
public class Person {
    {
        //代码块(匿名代码块)
    }
    static {
        //静态代码块
    }
    //程序执行的先后顺序 1 2 3
    //2:赋初始值
    {
        System.out.println("匿名代码块");
    }
    //1:只会执行一次
    static {
        System.out.println("静态代码块");
    }
    //3
    public Person() {
        System.out.println("构造方法");
    }
    public static void main(String[] args) {
        Person person1 = new Person();
        System.out.println("======================");
        Person person2 = new Person();
    }
}

  • 静态导入包
  • 被final关键字修饰的类不能有子类,不能被继承
//静态导入包,导入后可不输入Math.random(),直接使用random()
//被final修饰的类不能再被继承,不能有子类
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);
    }
}

posted @ 2021-11-16 22:48  wydilearn  阅读(43)  评论(0)    收藏  举报