【发布时间】:2020-01-20 15:41:50
【问题描述】:
所以,我是面向对象编程的新手。我已经编写了一个代码来连接复合类和组件类,我需要包含至少一个允许复合类与组件类通信以计算一些值的方法。但是我的Book 类没有显示作者的名字。
这是我的代码:
public class Author{
private String name;
private String yearOfBirth;
public Author ()
this.name = null;
this.yearOfBirth = null;
}
public Author (String aName)
{
this.name = aName;
this.yearOfBirth = null;
}
public Author(String aName, String aYear)
{
this.name = aName;
this.yearOfBirth = aYear;
}
public void setName(String aName)
{
this.name = aName;
}
public void setYearOfBirth(String aYear)
{
this.yearOfBirth = aYear;
}
public String getName()
{
return this.name;
}
public String getYearOfBirth()
{
return this.yearOfBirth;
}
public String toString()
{
return this.name + "(Born " + this.yearOfBirth + ")";
}
图书课
public class Book
{
private String title;
private String yearPublished;
private Author author;
public Book(String aTitle, String aYear,Author theAuthor)
{
this.title = aTitle;
this.yearPublished = aYear;
this.author = theAuthor;
}
public Book(String aTitle)
{
this.title = aTitle;
this.yearPublished = null;
this.author = new Author();
}
public void setAuthorName(String aName)
{
this.author.setName(aName);
}
public void setYearPublished(String aYear)
{
this.yearPublished = aYear;
}
public String getTitle()
{
return this.title;
}
public String getYearPublished()
{
if (this.yearPublished == null)
{
return "Unknown";
}
return this.yearPublished;
}
public String getAuthorName()
{
return this.author.getName();
}
public boolean isBorn()
{
return(Integer.parseInt
(this.author.getYearOfBirth()) < 1900);
}
public String toString()
{
{
return "Title: " + this.title + ", Author: " + this.author.getName() + ", yearPublished: " + this.yearPublished+ ".";
}
因此,当我尝试通过执行以下操作获取作者姓名时:Book hp = new Book ("Harry Potter","JK Rowling","2000"); 它会在显示窗格中显示
Compilation failed (20/01/2020 15:02:12)
Error: line 1 - no suitable constructor found for Book(java.lang.String,java.lang.String,java.lang.String)
如您所见,程序不会打印作者的姓名。
感谢所有帮助!
【问题讨论】:
-
这与您的
getAuthorName方法无关 - 您正在使用错误的参数调用Book构造函数,如错误消息所示。 -
请不要从您的问题中删除重要信息。它不仅适合您,也适合未来的读者。如果您删除代码,他们将没有关于正在发生的事情的上下文。
标签: java composite composite-component