0

found out in my own code the statement which looks like constructor for object instance, but it is actually not. I completely forgot where did I took the sample of such statement as for "Hi" print below, but it works like a constructor, while it is probably not. this code

public class TestSet {
    String hi="Hi";
    public TestSet(){
        System.out.println("Bye");
    }
    {
        System.out.println(hi);
    }

    public static void main(String s[]){
        new TestSet();
    }
}

actually prints out "Hi" and "Bye" aaaand, if TestSet would have a superclass, then putting "super" in "Hi" piece of code will not work. so what is it? I was trying to googling, but it is hard to formulate the query. thanks!

Павел
  • 677
  • 6
  • 21

1 Answers1

2

You statement that prints "Hi" is located in an instance initializer block. That block is copied to the beginning of each constructor of your class, and is executed prior to the body of the constructor, but after the super-class constructor is executed. Therefore new TestSet(); prints Hi followed by Bye, but you can't add calls to the super class constructor (super()) to the instance initializer block.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • I'm confused, how it is could be, that super constrctor called before, then called the instance block, if for instance I'm implicitly will call "super" from my constructor. thank you for naming this statement :) – Павел Jun 12 '16 at 12:47
  • I tryed to add parent class, and it works exactly as you described – Павел Jun 12 '16 at 12:49
  • 1
    @Павел The super-class constructor is always called (either explicitly or implicitly) from any constructor (unless that constructor invokes another constructor using `this()`), and it is called before the code of any instance initializer block. The code of the instance initializer block is called before the body of the constructor (which doesn't include the call to the super class constructor). – Eran Jun 12 '16 at 12:50