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

时间:2015-11-24 17:18:02

标签: java

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对象   来自现有对象但具有原始属性。

2 个答案:

答案 0 :(得分:1)

考虑使用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.

}

答案 1 :(得分:1)

  

我尝试使用b.clone,但b对象中没有克隆功能

实施Clonable中指定的clone方法,您可以调用它。

class Book implements Cloneable {
    int bookID = 0;

    public void setID(int i) {
        this.bookID = i;
    }

    public Book clone() throws CloneNotSupportedException {
        return (Book) super.clone();
    }
}

但我也希望Amir Afghani表示复制构造函数