gpt4 book ai didi

java - 返回与原始对象相同的对象的副本

转载 作者:行者123 更新时间:2023-12-02 04:09:50 25 4
gpt4 key购买 nike

package Test;
public class Test {
class Book implements Cloneable {
int bookID = 0;
public void setID(int i) {
this.bookID = i;
}
}
class bookFactory {
Book b;
bookFactory() {
b = new Book();
b.setID(20);
}
public Book GetBooks() {
return b;
//now i want to
//return a copy of b but it should be in the original state
}
}
}

我尝试使用b.clone,但b对象中没有克隆功能。 我可以简单地创建一个新对象,但我想返回 Book 对象 来自现有对象,但具有原始属性。

最佳答案

考虑使用copy constructor方法。

class Book { 

int id;

//your normal constructor
public Book(int id) {
this.id = id;
}

//your copy constructor
public Book(Book book) {
this.id = book.getId();
}

int getId() {
return this.id;
}

//Also, you will want to override hashCode & equals
//if you plan on testing for equality and using containers.

}

关于java - 返回与原始对象相同的对象的副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33899931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com