英文:
How to deep copy an object from another class?
问题
private String isbn;
private String title;
private String publisher;
private Object Author;
private int pages;
public Book(String isbn, String title, Author author, String publisher, int pages) {
this.isbn = isbn;
this.title = title;
this.publisher = publisher;
this.pages = pages;
this.Author = author;
}
public void setNumPages(int pageNum){
pages = pageNum;
}
public String getTitle() {
return title;
}
public Object getAuthor() {
return Author;
}
public String getIsbn(){
return isbn;
}
public String getPublisher() {
return publisher;
}
public String toString(){
return (title + ", " + getAuthor() + " (ISBN-10 #" + isbn + ", " + pages + " pages)");
}
public Book (Book other) {
this(other.isbn, other.title, other.getAuthor(), other.publisher, other.pages);
}
public boolean equals(Object obj) {
Book book = (Book) obj;
if (this.isbn.equals(book.getIsbn()) && this.title.equals(book.getTitle())
&& this.getAuthor().equals(book.getAuthor())) {
return true;
} else {
return false;
}
}
}
英文:
I have another class Author that returns the first and last name of an author and their email address. I need to do a deep copy of a book but it won't let me copy the author.
I thought I could just do use my getAuthor method but it isn't working.
Any help would be greatly appreciated. Thank you!!
private String isbn;
private String title;
private String publisher;
private Object Author;
private int pages;
public Book(String isbn, String title, Author author, String publisher, int pages) {
this.isbn = isbn;
this.title = title;
this.publisher = publisher;
this.pages = pages;
this.Author = author;
}
public void setNumPages(int pageNum){
pages = pageNum;
}
public String getTitle() {
return title;
}
public Object getAuthor() {
return Author;
}
public String getIsbn(){
return isbn;
}
public String getPublisher() {
return publisher;
}
public String toString(){
return (title + ", " + getAuthor() + " (ISBN-10 #" + isbn + ", " + pages + " pages)");
}
public Book (Book other) {
this(other.isbn, other.title, other.getAuthor(), other.publisher, other.pages);
}
public boolean equals(Object obj) {
Book book = (Book) obj;
if (this.isbn.equals(book.getIsbn()) && this.title.equals(book.getTitle())
&& this.getAuthor().equals(book.getAuthor())) {
return true;
} else {
return false;
}
}
}
答案1
得分: 2
你的 Author 字段具有 Object
类型:
private Object 作者;
你需要将 Object
更改为 作者
。
此外,考虑将字段从 作者
重命名为 author
,因为它可能会与 作者
类混淆。
英文:
Your Author field has the Object
type:
private Object Author;
You need to change Object
to Author
.
Also, consider renaming the field from Author
to author
because it may be confused with the Author
class.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论