所以,我是面向对象编程的新手。我做的下一excercises:从Book-class获取作者名简单
鉴于定义为具有以下属性的一类书:
Author author; String title; int noOfPages; boolean fiction;
写的每个属性的标准
get
/set
方法头。[编码]其实代码和编译基于锻炼methodscalled的属性和
get
/set
Book类1.
这是我的代码:
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: [email protected]
No. of pages: 300
Fiction: true
由于哟你可以看到,该程序不打印作者的名字。
我欣赏所有帮助!
你期望它打印什么?为什么? – shmosel
重写'toString'方法。当你将'Author'与'String'连接起来时,它被隐式调用。 – RamenChef