因此,我是面向对象编程的新手。我正在做下一个练习:
给定一个定义为具有以下属性的类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;
}
}
这是main的摘录:
Title: Beginning in Java Objects
Author: book.Author@15db9742
No. of pages: 300
Fiction: true
如您所见,该程序不会打印作者的姓名。
我感谢所有帮助!
最佳答案
如果要返回作者的姓名,请将其更改为:
public Author getAuthorsName(){
return this.author;
}
至:
public String getAuthorsName(){
return this.author.getName();
}
当前,您正在从方法中返回类
Author
的对象,因此要获取作者的姓名,您需要在调用代码中调用author.getName()
或更改现有方法以返回作者的姓名,如上所述。