Wednesday, 11 June 2014

MCQ #15

Question :

Consider the following  code : 

class Super { static String ID = "QBANK"; }
class Sub extends Super{
static { System.out.print("In Sub"); }
}
public class Test{
public static void main(String[] args){
System.out.println(Sub.ID);
}
}

What  will  be the output  when  class Test  is run ?

A. I t  will  print  In Sub and QBANK.
B. I t  will  print  QBANK.
C. Depends on  the implementation  of  JVM.
D. It  will  not  even  compile.
E. None of  the above.

Answer

Answer is option B.

Explanation 

It would look like the program would print  "In sub" followed by QBANK and the option would be A but it is not. 

Since ID is inherited from the Super class it is really the Super class that is initialized and not the Sub class. So that static method in Sub class will not get printed. 

A class is initialized only when it's content (variables/methods) which are not inherited gets referenced. Not otherwise.

From JLS 12.4.1:
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
  • T is a class and an instance of T is created.
  • T is a class and a static method declared by T is invoked.
  • A static field declared by T is assigned.
  • A static field declared by T is used and the field is not a constant variable (§4.12.4).
  • T is a top-level class, and an assert statement (§14.10) lexically nested within T is executed.

No comments:

Post a Comment

t> UA-39527780-1 back to top