Java - What is the output: call base constructor

Question

What is the output of the following code.

class SuperBase {

  static {
    System.out.println("SuperBase 1");
  }

  SuperBase() {
    System.out.println("base default.");
  }

  SuperBase(int a) {
    System.out.println(a);
  }

  void getInt() {
    System.out.println(1);
  }
}

public class Main extends SuperBase {

  static {
    System.out.println("Super 1");
  }

  {
    System.out.println("Super initialize block.");
  }

  Main() {
    // without call to super(), SuperBase() will be called automatically.
    System.out.println("Super.");
  }

  void getInt() {
    super.getInt();
    System.out.println(2);
    super.getInt();
  }

  void getInt2() {
    super.getInt();
    System.out.println(2);
    super.getInt();
  }

  public static void main(String[] args) {
    Main s = new Main();
    s.getInt();
    s.getInt2();
  }
}


Click to view the answer

SuperBase 1
Super 1
base default.
Super initialize block.
Super.
1
2
1
1
2
1

Demo

class SuperBase {

  static {/*from  w ww  .  ja  va  2s . c  o m*/
    System.out.println("SuperBase 1");
  }

  SuperBase() {
    System.out.println("base default.");
  }

  SuperBase(int a) {
    System.out.println(a);
  }

  void getInt() {
    System.out.println(1);
  }
}

public class Main extends SuperBase {

  static {
    System.out.println("Super 1");
  }

  {
    System.out.println("Super initialize block.");
  }

  Main() {
    // without call to super(), SuperBase() will be called automatically.
    System.out.println("Super.");
  }

  void getInt() {
    super.getInt();
    System.out.println(2);
    super.getInt();
  }

  void getInt2() {
    super.getInt();
    System.out.println(2);
    super.getInt();
  }

  public static void main(String[] args) {
    Main s = new Main();
    s.getInt();
    s.getInt2();
  }
}

Related Topic