当我从 hp 变量中检查作者的出生年份并检查对象时...它显示 null 作为出生年份,但在 jkr 变量中它显示出生年份为 1965 年而不是 null。为什么它通过 hp 显示为 null 以及如何让它显示出生年份?
以下是我执行的内容: 第一:
Author jkr = new Author("JK Rowling", "1965");
检查变量时,yearOfBirth
显示良好
然后:
Book hp = new Book("Harry Potter and the Philosophers Stone",
"1997",
new Author("JK Rowling"));
检查时yearOfBirth
显示为null
?我希望图书代码显示为
例如:书名:哈利·波特,作者:JK Rowling**(出生于 1900 年)**...以及出生年份
最佳答案
Book hp = new Book("Harry Potter and the Philosophers Stone",
"1997",
new Author("JK Rowling"));
在这种情况下,您不会在 Author
的构造函数中初始化 yearOfBirth
,因此该字段将采用您在单参数构造函数中给出的值,即为null
。
public Author (String aName) {
this.name = aName;
this.yearOfBirth = null; // <--- HERE
}
如果您想初始化该字段,您可以使用 Author
的其他构造函数(就像您在第一个示例中所做的那样)或在此构造函数中为其分配默认值。
关于java - 执行以下代码时,Author 类的yearofBirth 出现为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59828382/