Java static关键字

Java static关键字

static也就是静态的意思:

  1. 静态变量---->可以直接访问
  2. 静态方法---->可以直接调用
  3. 静态代码块---->可以直接用main方法输出
  4. 静态导入包---->可以直接调用最后的方法

示例:

package com.oop.demo07;

//static
//静态变量
public class Students {
    private static int age;//静态的变量
    private double score;//非静态的变量

    //测试类
    public static void main(String[] args) {
        Students s1 = new Students();
        System.out.println(s1.age);
        System.out.println(s1.score);
        System.out.println(Students.age);//静态变量可以直接使用类名访问
        //System.out.println(Students.score);代码报错,因为变量不是静态变量,不可直接访问
    }

}
package com.oop.demo07;

//静态方法
public class Teacher {
    //非静态方法
    public void run(){

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

    }

    //测试类
    public static void main(String[] args) {
        new Teacher().run();//调用方法
        new Teacher().go();//调用方法
        go();//可以直接调用静态方法
        //run();代码报错,不可以直接调用

    }

}
package com.oop.demo07;

//静态代码块
public class Person {
    //匿名代码块,第二输出
    {
        System.out.println("匿名代码块");
    }
    //静态代码块,第一输出,和类一起加载,不用写代码,用main方法直接运行就可以输出
    //而且静态代码块,只会执行第一个new的对象
    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 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(Math.random());//Math.random() 生成随机数的代码
        System.out.println(random());//因为上面有静态导入包,所以可以直接写random()
        System.out.println(PI);//PI 常量的代码
    }
    /*
    输出的结果为:0.7559324063883691
        0.8503487780379054
        3.141592653589793
     */
}
posted @ 2021-10-18 22:41  Liquor无言  阅读(25)  评论(0)    收藏  举报