遇到此问题时,我正在练习圆顶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();
在您当前的代码中,使用将不起作用,因为您尚未定义它。
仅当不存在其他构造函数时,才会自动生成默认构造函数。
您不必为类提供任何构造函数,但是在执行此操作时必须小心。编译器自动为任何没有构造函数的类提供无参数的默认构造函数。此默认构造函数将调用超类的无参数构造函数。在这种情况下,如果超类没有无参数构造函数,则编译器将抱怨,因此您必须验证它是否具有。如果您的类没有显式超类,则它具有Object的隐式超类,该类确实具有无参数构造函数。
来源:http : //docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句