一文带你吃透 Java 中 static 关键字用法
2019年1月4日约 952 字大约 3 分钟
一、介绍
关于 Java 中static关键字,基本也是面试必问,今天面试我问你static关键字有哪些用法,如果你回答能修饰变量、修饰方法,我会认为你合格,如果能答出修饰静态代码块,我会认为你不错,如果能答出修饰静态内部类,我会认为你很好,如果能答出能静态导包,我会认为你非常热衷研究技术。
显然,回答不一样,体现的基础水平也不一样,下面我们一起来看看这个关键字到底有哪些用法。
二、场景使用
2.1、修饰变量
被static修饰的变量属于类的成员变量,如下例子,外部可以通过Test.hello来直接获取变量内容。
public class Test{
    //static修饰变量
    public static String hello = "hello";
}2.2、修饰方法
被static修饰的方法属于类的成员方法,如下例子,外部可以通过Test. hello()来直接获取方法返回内容。
public class Test{
    
    /**
     * static修饰方法
     * @return
     */
    public static String hello(){
        return "Hello World";
    }
}2.3、修饰静态代码块
static关键字也可以修饰代码块,在类加载期间会被执行,有且只执行一次!
public class Test{
    
    /**
     * static修饰代码块
     * @return
     */
    static {
        System.out.println("Hello World");
    }
}2.4、修饰静态内部类
static关键字还可以修饰内部类,如果内部类的变量是成员变量,如下例子,可以直接通过Hello.content获取里面的内容。
public class Test{
    
    /**
     * static修饰内部类
     * @return
     */
    public static class Hello{
        public static String content = "hello World";
    }
    public static void main(String[] args) {
        //打印Hello的内容
        System.out.println(Hello.content);
    }
}修饰静态内部类的使用案例比较多,比如常用的单例设计模式,内容如下:
public class Singleton {
    
    private static class SingletonHolder {
        //通过静态内部类来创建对象
        private static final Singleton INSTANCE = new Singleton();
    }
    
    /**私有化构造方法*/
    private Singleton (){}
    
    /**通过静态内部类方法获取对象*/
    public static final Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}2.5、静态导包
静态导包,这个估计很少人能想的到,因为使用的非常少,用法例子如下:
先创建一个类TestA,内容如下:
package com.example.java.statics;
public class TestA {
    public static void hello(){
        System.out.println("hello World");
    }
}再创建一个类TestB,内容如下:
package com.example.java.statics;
/**静态导包*/
import static com.example.java.statics.TestA.hello;
public class TestB {
    public static void main(String[] args) {
        //调用TestA类中的hello()方法
        hello();
    }
}其中静态导包的方法,如下:
import static com.example.java.statics.TestA.hello;通过这种方式,TestB就可以直接调用TestA中的hello()方法进行使用了。
三、参考
jdk1.7 & 1.8
作者:潘志的技术笔记
出处:https://pzblog.cn/
版权归作者所有,转载请注明出处
