Java中的static关键字详解

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) {
        Student student = new Student(); //没有static 的方法需要实例化
        student.run();

        Student.go(); //有static 的方法,可以直接用类名点,或者直接写方法名()
        go();
    }
}

分析:有static修饰的方法和变量都可以直接用 (类名.变量|类名.方法名()),没有static 的修饰需要实例化(new)这个类,通过对象才能使用这个变量和方法

**例子2:**static代码块

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

结果:

静态代码块
匿名代码块
构造方法
===============
匿名代码块
构造方法

分析:静态代码块比匿名代码块,构造方法更快的执行,而且静态代码块只能执行一次

例子3:

//静态导入包
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()); //没有静态导入包
        System.out.println(random()); //有静态导入包
        System.out.println(PI);
    }
}

静态导入包好可以偷懒一下,不用写类名,直接使用那个类的方法和变量

你可能感兴趣的:(Java基础学习)