-2

May someone explain this bit of code? Also, how does the static affect this? Sorry for errors that may be there...

class A
{   static
    {
        System.out.println("THIRD");
    }
}
class B extends A
{   static
    {
        System.out.println("SECOND");
    }
}
class C extends B
{   static
    {
        System.out.println("FIRST");
    }
}
public class MainClass
{   public static void main(String[] args)
    {
        C c = new C();
    }
}

1 Answers1

1

Since superclass or superclasses are initialized before subclasses, when you create an object of C class, JVM internally initializes B class before C class as C class extends B class.

Again since B class extends A class, so when B class is initialized, JVM internally initializes A class before loading B class.

That means, in this scenario, JVM initializes the class in main memory in the following order:

Class A ---> Class B ---> Class C

Since static block is executed when the class is actively used for the first time. First A class static block will be executed, then B class static block will be executed and lastly C class static block will be executed.

Output:

THIRD
SECOND
FIRST
S.Mandal
  • 172
  • 1
  • 10
  • 2
    This is not correct. In fact, classes (and hence static initializers) are initialized in the order that they are first used. This is not the same as class loading order. See the answers to the dup link question for more details, including links to the relevant parts of the Java Language Specification, etc. – Stephen C Mar 29 '20 at 03:15
  • I think when the class is first loaded in main memory, then only static initializers are executed. And class is loaded only when it is used for the first time. Correct me if I am wrong. – S.Mandal Mar 29 '20 at 03:35
  • 1
    I am correcting you. Read JLS https://docs.oracle.com/javase/specs/jls/se11/html/jls-12.html#jls-12.4.1 and https://docs.oracle.com/javase/specs/jls/se11/html/jls-12.html#jls-12.4.2. Take your time, it is not an easy read ... if you have never read the JLS before. (If it is too hard understand, the short version is my comment above!) – Stephen C Mar 29 '20 at 03:49
  • I have got the point. Thanks :) – S.Mandal Mar 29 '20 at 04:01
  • Updated my answer. – S.Mandal Mar 29 '20 at 04:14