Class initialization in Java

Class initialization means initializing all static members of the class. Class in Java is initialized when :

  • An instance of the class is created using either new() keyword or using reflection via Class.forName(String name, boolean initialize, ClassLoader loader) with second parameter set to true
  • A static method of class is invoked
  • A static field of class is assigned
  • A static field of class is used which is not a constant variable

Besides, some methods of the classes from java.lang.reflect package may cause the class to be initialized.

How class is initialized in Java :

  • Classes are initialized from top to bottom so field declared on top initialized before field declared in bottom
  • Super Class is initialized before Sub Class or derived class in Java
  • If Class initialization is triggered due to access of static field, only Class which has declared static field is initialized and it doesn’t trigger initialization of super class or sub class even if static field is referenced by Type  of Sub Class, Sub Interface or by implementation class of interface
  • interface initialization in Java doesn’t cause super interfaces to be initialized
  • static fields are initialized during static initialization of class while non static fields are initialized when an instance of the class is created. It means static fields are initialized before non-static fields in Java

Leave a Reply

Your email address will not be published. Required fields are marked *