Difference between loading a class and instantiating it

后端 未结 5 1426
抹茶落季
抹茶落季 2021-02-08 11:56

Could someone explain what is the difference between Class loading and instantiating a Class. When we load a class with Static variable does it also get instantiated the same ti

5条回答
  •  孤街浪徒
    2021-02-08 12:56

    Here is some nice explanation(with an example and observation)

    When a class is loaded and initialized in JVM - Java

    When Class is loaded in Java

    Class loading is done by ClassLoaders in Java which can be implemented to eagerly load a class as soon as another class references it or lazy load the class until a need of class initialization occurs. If Class is loaded before its actually being used it can sit inside before being initialized. I believe this may vary from JVM to JVM. While its guaranteed by JLS that a class will be loaded when there is a need of static initialization.

    When a Class is initialized in Java

    When a Class is initialized in Java After class loading, initialization of class takes place which means initializing all static members of class. A Class is initialized in Java when :

    1) an Instance of class is created using either new() keyword or using reflection using class.forName(), which may throw ClassNotFoundException in Java.

    2) an static method of Class is invoked.

    3) an static field of Class is assigned.

    4) an static field of class is used which is not a constant variable.

    5) if Class is a top level class and an assert statement lexically nested within class is executed.

    Hope that helps.

提交回复
热议问题