I'm trying to understand Java super()
constructor. Let's take a look in the following class:
class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point() {
this(0, 0);
}
}
This class will compile. If we create a new Point
object say Point a = new Point();
The constructor with no parameters will be called: Point()
.
Correct me if I'm wrong, before doing this(0,0)
, the Class
constructor will be called and only then Point(0,0)
will be called.
If this is true, is it correct to say that super()
is being called by default?
Now let's look at the same code with a small change:
class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point() {
super(); // this is the change.
this(0, 0);
}
}
Now, the code won't compile because this(0,0)
is not in the first line of the constructor. This is where I get confused. Why the code won't compile? Doesn't super()
is being called anyway? (The Class constructor as described above).