当我遇到这个问题时,我正在练习 dome Java OO 原则。我创建 POJO 并尝试从中创建对象时,如果未定义空构造函数,它将无法编译。
我觉得这很奇怪,因为我曾经这样做过,而且 JVM 为我提供了一个默认的。它是 Java 7 中的新功能吗?我错过了什么吗?
这是我做的示例代码
public class Dog {
String name;
String race;
int age;
/*
public Dog() {
If this isn't included, it doesn't compile if I try to
create no-args objects.
}*/
public Dog (String _name) {
this.name = _name;
}
public Dog (String _name, String _race) {
this.name = _name;
this.race = _race;
}
public Dog (String _name, String _race, int _age) {
this.name = _name;
this.race = _race;
this.age = _age;
}
最佳答案
使用 Dog newDog = new Dog();
在您当前的代码中将不起作用,因为您尚未定义它。
默认构造函数将仅在没有其他构造函数存在的情况下自动生成。
You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.
来源:http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
关于java - 从什么时候开始在 Java 中必须包含一个空的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20445249/