Monday, 5 February 2018

java - Constructor call must be the first statement in a constructor





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.



Answer



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.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...