static关键字

static

Student.java

package com.oop.demo07;

//static
public class Student {

    private static int age;//静态的变量  多线程!
    private double score;//非静态变量

    public void run(){//非静态方法可以调用静态方法中所有

        go();
    }

    public static void go(){

    }

    public static void main(String[] args) {

        new Student().run();
        Student.go();//go();
        //run();无法直接调,static和类一起加载,那时还没有run();




        /*
        Student s1 = new Student();
        System.out.println(Student.age);//类变量 静态的 用类
        System.out.println(s1.age);//用对象
        System.out.println(s1.score);
         */


    }

}

Person.java

package com.oop.demo07;

public class Person {

    //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();

    }
}

Test.java

package com.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);
    }
}

posted @ 2022-04-30 20:08  大白很白  阅读(21)  评论(0)    收藏  举报