为什么在Java中编写带参数构造函数时,默认的无参数构造函数会失败?

huangapple go评论53阅读模式
英文:

Why does the default parameter-free constructor fail when a parameter-constructor is written in Java?

问题

为什么在Java中提供参数构造函数时默认的无参数构造函数会失败?

这个设计的目的是什么?

例如:

class Father {
    public String name = "Father";

    public Father(String name) {
        this.name = name;
    }
}

public class Test {
    public static void main(String[] args) {
        Father p = new Father();  //错误
    }
}
英文:

Why does the default parameter-free constructor fail, when a parameter-constructor is given in Java?

What's the point of this design?

For example:

class Father {
    public String name = "Father";

    public Father(String name) {
        this.name = name;
    }
}

public class Test {
    public static void main(String[] args) {
        Father p = new Father();  //Error
    }
}

答案1

得分: 1

如果您没有提供构造函数,编译器将生成一个默认的零参数构造函数。

如果您提供了任何构造函数,编译器将不会生成其他构造函数。在这种情况下,单参数构造函数由您提供,因此编译器不会生成默认构造函数。

英文:

If you supply no constructor, the compiler will generate a default, zero-argument constructor.

If you supply any constructors, the compiler will not generate any others. In this case, the single-argument constructor is supplied by you, so the compiler does not generate a default constructor.

huangapple
  • 本文由 发表于 2020年8月11日 11:14:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/63350960.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定