Is the class loaded when it's reference is declared?

前端 未结 2 1366
被撕碎了的回忆
被撕碎了的回忆 2021-01-14 09:18

Does creating a reference to an object of a class cause the class to be loaded ? Static variables are initialized when the class is loaded, so considering the following code

2条回答
  •  情话喂你
    2021-01-14 09:38

    Yes. Static initializers are called when a class method is called or an instance is instantiated.

    From your example you can do one of the following:

    1. Create New Instance

    public static void main(String[] args) {
        A a = new A();
    }
    

    2. Call Static Class Method

    public static void main(String[] args) {
        int f = A.f();
    }
    

提交回复
热议问题