What will be the output of the following code?

class Super { static String ID = "QBANK"; }
class Sub extends Super{
  static { System.out.print("In Sub"); }
class Test{
  public static void main(String[] args) {
A static block will be executed only during the class initialization.
A class does not need to be initialized, in order to access static fields of a parent class.
In order to initialize a class one of the following should happen:
1. A class instance or an array of class type is created.
2. A read or a write operation on a non-constant field of the same class (i. e. not inherited) is performed.
3. A method implemented in the same class (i. e. not inherited) should be invoked (including main method).
Since the Sub class has access to the ID variable (via inheritance) - the string "QBANK" will be printed, with no issues.
Since initialization of Sub class does not happen - the static block is not executed and the "In Sub" string will not be printed.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback