理解Java super()构造函数

Rom*_*man 2 java constructor super

我正在尝试理解Java super()构造函数.我们来看看下面的课程:

class Point {
    private int x, y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public Point() {
        this(0, 0);
    }
}
Run Code Online (Sandbox Code Playgroud)

这个类将编译.如果我们创建一个新Point对象Point a = new Point();,那么将调用没有参数的构造函数:Point().

如果我错了,请纠正我,在做之前this(0,0),Class将调用构造函数,然后Point(0,0)才会调用它.如果这是真的,那么说super()默认情况下是否正确?

现在让我们看一下相同的代码并进行一些小改动:

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在,代码将无法编译,因为this(0,0)它不在构造函数的第一行.这是我感到困惑的地方.为什么代码不能编译?不super()被称为无论如何?(如上所述的类构造函数).

Bla*_*nka 5

this(0, 0);将调用同一类的构造函数,super()并将调用类的超类/父Point类.

现在,代码将无法编译,因为此(0,0)不在构造函数的第一行.这是我感到困惑的地方.为什么代码不能编译?是不是还要调用super()?

super()必须是构造函数的第一行,也this()必须是构造函数中的第一行.所以两者都不能在第一行(不可能),这意味着,我们不能在构造函数中添加两者.

作为关于您的代码的说明:

this(0, 0);将调用带有两个参数(在Point类中)的构造函数,并且两个参数构造函数将super()隐式调用(因为您没有显式调用它).