If you have a constructor which calls this() when is super() called? In the first constructor called? Or in the last constructor without the keyword this()?
Main calls: new B()
public class A {
public A(){
System.out.print("A ");
}
}
public class B extends A {
public B(){
// is super called here? Option 1
this(1);
System.out.print("B0 ");
}
public B(int i){
// or is super called here? Option 2
System.out.print("B1 ");
}
}
In this example the Output is: "A B1 B0". But it isn't clear to me, if the super() constructor is called at Option 1 or Option 2 (because the Output would be the same, in this case).
When instantiating a new object, using
new B(), it automatically calls the no-arguments constructor. In your case,public B().In the no-arguments constructor: Because your constructor specified either a call to another constructor (using
this()) or a manually specified call to the superclass constructor (usingsuper()), there is no other call to another constructor. If your constructor was to only have the printing line (System.out.print("B0);),super()would have been automatically called. Now, you're callingthis(1), so your first constructor won't output anything yet, but will go to your second constructor, having anintargument.In the second constructor (with int argument): As I specified already, if your constructor doesn't have an explicit call to
this()orsuper(), it automatically callssuper()(without any arguments unless manually specified). Becausesuper()must always be the first call in a constructor, it is executed before yourprint, meaning thatA()is called. The first thing to be printed would beA. Moving on, there will beB1printed.Back in your first constructor (no args):
this(1)has already been called, so it moves to the next statement, the one that prints something. SoB0will be printed.Now, as a recap, for a proper answer:
super()is automatically called only inpublic B(int i), because you already specified a call tothis()in your first constructor, andsuper()is only called automatically when you don't specifythis()or an explicit call tosuper().