所以,我是面向对象编程的新手。我正在做下一个练习:
给定一个定义为具有以下属性的类Book:
Author author;
String title;
int noOfPages;
boolean fiction;
为每个属性编写标准get
/ set
方法标题。
[编码]实际上根据练习1中所要求的属性和get
/ set
方法编写和编译Book类。
这是我的代码:
public class Author {
//private variable
private String name;
private String gender;
//constructor
public Author (String name, String gender){
this.name = name;
this.gender = gender;
}
//getters
public String getName(){
return name;
}
public String getGender(){
return gender;
}
public class Book {
//private variables
private Author author;
private String title;
private int noOfPages;
private boolean fiction;
//constructor
public Book(String title, int noOfPages, boolean fiction){
this.author=new Author ("Jacquie Barker","Female");
this.title = title;
this.noOfPages=noOfPages;
this.fiction = fiction;
}
//getters
public Author getAuthorsName(){
return this.author;
}
public String getTitle(){
return title;
}
public int getNoOfPages(){
return noOfPages;
}
public boolean getFiction(){
return fiction;
}
//setters
public void setAuthor(Author newAuthor){
author=newAuthor;
}
public void setTitle (String title){
this.title=title;
}
public void setNoOfPages(int noOfpages){
this.noOfPages=noOfpages;
}
public void setfiction(boolean fiction){
this.fiction=false;
}
public String toString(){
return "Title: " + this.title + "\n"+"Author: " + this.author + "\n" +
"No. of pages: " + this.noOfPages + "\n" + "Fiction: " + this.fiction;
}
}
以下是主要的摘录:
Title: Beginning in Java Objects
Author: book.Author@15db9742
No. of pages: 300
Fiction: true
如您所见,该程序不会打印作者的姓名。
我感谢所有人的帮助!
答案 0 :(得分:2)
这里有两种选择。首先,您可以简单地重构Book.toString()
方法中的代码以打印作者的实际名称:
public String toString(){
return "Title: " + this.title + "\n"+"Author: " + this.author.getName() + "\n" +
"No. of pages: " + this.noOfPages + "\n" + "Fiction: " +
}
其次,您可以覆盖toString()
类中的Author
方法以返回作者的姓名。然后,您可以保留Book.toString()
方法,因为当您尝试打印toString()
对象时,Java会调用此Author
方法:
public class Author {
// print the author's name when an Author object appears in a print statement
public String toString() {
return this.name;
}
}
然后和你一样:
public class Book {
public String toString(){
return "Title: " + this.title + "\n"+"Author: " + this.author + "\n" +
"No. of pages: " + this.noOfPages + "\n" + "Fiction: " + this.fiction;
}
}
答案 1 :(得分:1)
您应该在Author类中实现toString。
public class Author {
//private variable
private String name;
private String gender;
//constructor
public Author (String name, String gender){
this.name = name;
this.gender = gender;
}
...
public String toString() {
return "Name " + name + "\t Gender: " + gender + "\n"; //Somethign like this.
}
}
答案 2 :(得分:1)
如果您使用的是Eclipse,IntelliJ或NetBeans等IDE,则可以让它们生成这些标准的getter和setter。浏览菜单。
这样就不存在拼写错误(如setfiction
中所述,f
应该是大写字母。)
由于您是初学者,您应该先自己编写,然后让它们自动生成,这样您就可以比较您的解决方案。
答案 3 :(得分:0)
如果要返回作者姓名,请将其更改为:
public Author getAuthorsName(){
return this.author;
}
到:
public String getAuthorsName(){
return this.author.getName();
}
目前您正在从您的方法返回类Author
的对象,因此要获取作者的姓名,您需要在调用代码中调用author.getName()
或更改现有方法以返回作者的如上所述的名称。