Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Java super() constructor

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).

like image 660
DifferentPulses Avatar asked May 17 '26 17:05

DifferentPulses


1 Answers

this(0, 0); will call, constructor of the same class and super() will call super/parent class of Point class.

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?

super() must be the first line of the constructor and also this() must be the first line in the constructor. So both cannot be in the first line(not possible), that means, we cannot add both in a constructor.

As a explonation about your code:

this(0, 0); will call to the constructor that takes two parameters(in Point class) and that two parameter constructor will call to the super() implicitly(because you didnt call it explicitly).

like image 60
Blasanka Avatar answered May 19 '26 05:05

Blasanka