"Constructor call must be the first statement in a constructor" getting error in Java code?

I am getting two errors in this code

  1. Constructor call must be the first statement in a constructor.

  2. Implicit super constructor Parent() is undefined. Must explicitly invoke another constructor.

So please help me to resolve these issues.

class Parent
{
  public Parent(int x, int y,int z)
  {
    System.out.println("Created Parent");
  }
}
public class Child extends Parent
{
  Child(int x)// error 2   
  {

  }
  Child(int x, int y)// error 2
  {
  }
  Child(int x, int y, int z)
  {
    this(x);
    super(x,y,z);// error 2
    System.out.println("Creating child");
    this(x,y);// error 1
  }
  public static void main(String [] args)
  {
    Child c=new Child(1,2,3);
  }
}
Jon Skeet
people
quotationmark

There are four things you need to understand:

  • If you don't specify any explicit constructor call, the compiler inserts a call to super() for you.

  • There must be exactly one constructor call for any constructor- either explicit or the implicit super() call. (You've got three in your Child(int, int, int) constructor.

  • An explicit constructor call must be the very first statement in the constructor body.

  • You can only call a constructor which actually exists - so a call to super() from Child is looking for a parameterless constructor in Parent, which doesn't exist.

One frequent pattern is to have a "master" constructor which other constructors in the same class chain to, and then that one chains to the superclass. For example:

Child(int x)
{
    this(x, 0); // Chains to the Child(int, int) constructor, defaulting y to 0
}

Child(int x, int y)
{
    // Chains to the Child(int, int, int) constructor, defaulting z to 0
    this(x, y, 0);
}

Child(int x, int y, int z)
{
    super(x, y, z);
    System.out.println("Creating child");
}

people

See more on this question at Stackoverflow