所以,我是面向對象編程的新手。我做的下一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