Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor call must be the first statement in a constructor [duplicate]

I do not understand why the below code displays the error Constructor call must be the first statement in a constructor if I shift this(1); to the last line in the constructor.

package learn.basic.corejava;

public class A {
    int x,y;

    A()
    {     
        // this(1);// ->> works fine if written here
        System.out.println("1");
        this(1);  //Error: Constructor call must be the first statement in a constructor
    }

    A(int a)
    {
        System.out.println("2");
    }

    public static void main(String[] args) { 
        A obj1=new A(2);  
    }   
}

I've checked many answers on this topic on StackOverflow but I still could not understand the reason for this. Please help me to make clear about this error with some easy example and explanation.

like image 371
beginner Avatar asked Nov 25 '13 16:11

beginner


2 Answers

As you know, this works:

A() {
      this(1);
      System.out.println("1");
}

Why? because it's a rule of the language, present in the Java Language Specification: a call to another constructor in the same class (the this(...) part) or to a constructor in the super class (using super(...)) must go in the first line. It's a way to ensure that the parent's state is initialized before initializing the current object.

For more information, take a look at this post, it explains in detail the situation.

like image 144
Óscar López Avatar answered Sep 23 '22 09:09

Óscar López


The error tells you the problem

A()
{     
      System.out.println("1");
      this(1);  //Error: Constructor call must be the first statement in a constructor
}

i.e. you must call the constructor first

A()
{
      this(1);
      System.out.println("1");
}

this also applies to calls to super

class B extends A
{
    B()
    {
        super();
        System.out.println("1");
    }
}

the reason being is answered here

like image 28
T I Avatar answered Sep 22 '22 09:09

T I