Difference between loading a class and instantiating it

后端 未结 5 1430
抹茶落季
抹茶落季 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 13:02

    A class is loaded when it is referenced (e.g. by Class.forName()).

    You instanciate an object by creating an instance, e.g.

    Object o = new Object();
    

    You can also instanciate an object by using reflection.

    static members of a class are instanciated when the class is loaded, e.g.

    public class Sample {
        private static int variable = 10;
    }
    

    When I now load the class (e.g. by Class.forName("Sample");) Then the variable variable is initialized with the value 10.

    If you are creating a new instance of a class and it is not loaded before the class will be loade before (atomatically). So the construct Class.forName() is only needed under special circumstances (if the class is not known by compile time e.g.).

提交回复
热议问题