java - 从什么时候开始在 Java 中必须包含一个空的构造函数?

标签 java oop

当我遇到这个问题时,我正在练习 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/

相关文章:

java - 如何在Java中指定夏令时转换后的时间

java - 为什么重定向到 catalina.out 的应用程序 (sysout/syserr) 日志没有时间戳?

java - 继承问题/问题

c++ - X() = delete; 构造函数的区别和私有(private) X();

c++ - 未定义基类,但包含其 header

java - 已检查和未检查的自定义异常

java - 它如何返回 NullPointerException?

javascript - typescript :如何导入类 ("Uncaught ReferenceError")

C++:使用计算参数调用基类构造函数

java - 登录认证编程模式