多个构造函数不起作用

Rog*_*r W 0 java constructor

好的,所以我试图学习如何使用多个构造函数,并且不能完全理解为什么调用这些不同的方法不起作用 - 实际上第一个方法不会编译.

谢谢你的关注...

    // Compile error here. I'm trying to call the 2nd Counter method with default values.
    public void Counter() {
    this.Counter(0, false); 
}

// Here I'm trying to enable a call to the Counter method with integer and boolean attributes in its call.

    public Counter(int startingValue, boolean check) {
    this.startingValue = startingValue;
    this.check = check;
}
Run Code Online (Sandbox Code Playgroud)

rge*_*man 5

原因是你的第一个Counter"构造函数"根本不是构造函数 - 它是一个void返回类型的方法.

通过删除返回类型使其成为构造函数.

public Counter() {
    this(0, false);
Run Code Online (Sandbox Code Playgroud)

然后你可以调用另一个构造函数this.