0

Is it possible to call the constructor of a parent-class not at the first line of the child?

I would like to build something like this (see constructor B).

class A
{
   public A () {}
   public A (int x) { // do something }
}

class B extends A
{
  public B (int y)
  {
    if (y > 0) { super (y); }
  }
}

I think with the existence of a default-constructor it is called automatically. Without it it would need to call super for the 1st line in B ().

Is it possible to call the other constructor (with the parameter) AFTER the 1st line - or have the same effect?

chris01
  • 10,921
  • 9
  • 54
  • 93
  • [This question might help](https://stackoverflow.com/questions/1168345/why-do-this-and-super-have-to-be-the-first-statement-in-a-constructor) – Draken Aug 07 '18 at 15:20
  • Adding that condition might be confusing anyways but if you have to do it, why not use a marker/default value, e.g. like `super(y > 0 ? y : default)`? – Thomas Aug 07 '18 at 15:21

3 Answers3

2

It's not possible. super() must always be the first statement of the child's constructor. See for more details on why: Why do this() and super() have to be the first statement in a constructor?

Joel Rummel
  • 802
  • 5
  • 18
1

Invocation of a superclass constructor must be the first line in the subclass constructor.

https://docs.oracle.com/javase/tutorial/java/IandI/super.html

Rishikesh Dhokare
  • 3,559
  • 23
  • 34
1

Actualy for such questions exist JAVADOC: https://docs.oracle.com/javase/tutorial/java/IandI/super.html

And there is pretty well explained.

The logic you would like to achieve you can do in a different way

class A
{
   public A () {}
   public A (int x) { 
        doSomething(x); 
   }
   protected doSomething(int x){// do something}
}

class B extends A
{
  public B (int y)
  {
    if(y > 0){
     doSomething(y);
    }
  }
}
Simion
  • 353
  • 1
  • 9
  • this is `Java language` thing, not a JVM one - JVM does not care what first to execute, `javac` does – Eugene Aug 13 '18 at 19:36