Java OCA OCP Practice Question 2970

Question

Given:

1. abstract class Shape {  
2.   static String s = "-";  
3.   Shape() {  s += "v"; }  
4. }  /*from w  ww  .j  av a  2s  .  c o  m*/
5. public class Main extends Shape {  
6.   Main() { this(7); s += "e"; }  
7.   Main(int x) { s += "e2"; }  
8.   public static void main(String[] args) {  
9.     System.out.print("made " + s + " ");  
10.   }  
11.   static {    
12.     Main e = new Main();  
13.     System.out.print("block " + s + " ");   
14. } } 

What is the result?

  • A. made -ve2e
  • B. block -ee2v
  • C. block -ve2e
  • D. made -eve2 block -eve2
  • E. made -ve2e block -ve2e
  • F. block -ve2e made -ve2e
  • G. block -ve2e made -ve2eve2e
  • H. Compilation fails


F	 is correct.

Note

The static initialization block is the only place where an instance of Main is created.

When the Main instance is created, Main's no-arg constructor calls its 1-arg constructor, which then calls Shape's constructor (which then secretly calls Object's constructor).

At that point, the various constructors execute, starting with Object's constructor and working back down to Main's no-arg constructor.




PreviousNext

Related