[英]How to create an object using same type of object
I wonder if it is possible to get a new instance of an object, using other object of the same type. 我想知道是否有可能使用相同类型的其他对象获取对象的新实例。
public class Vegetable{
private int ...
//a lot of fields
public Vegetable(Vegetable v) {
//some magic here
}
}
I am looking for an option, where i wouldn't copy each single field manually in the constructor, but rather use something like super(v) . 我正在寻找一个选项,我不会在构造函数中手动复制每个单独的字段,而是使用像super(v)这样的东西。
Java does not provide a default copy constructor. Java不提供默认的复制构造函数。
However, Java does provide a method Object.clone()
. 但是,Java确实提供了Object.clone()
方法。 You can call it on instances of classes that implement Cloneable. 您可以在实现Cloneable的类的实例上调用它。 Otherwise, it will throw CloneNotSupportedException. 否则,它将抛出CloneNotSupportedException。
The default implementation creates a shallow copy . 默认实现创建浅拷贝 。 If your object contains references to other objects, only the references are copied. 如果对象包含对其他对象的引用,则仅复制引用。 This is usually not what you want. 这通常不是你想要的。 To create a deeper, more independent copy, you can extend the default implementation. 要创建更深入,更独立的副本,可以扩展默认实现。
You can create your own copy constructor, and this is sometimes useful. 您可以创建自己的复制构造函数,这有时很有用。 However, unlike clone()
, a copy constructor will not necessary create another instance of the same class. 但是,与clone()
不同,复制构造函数不必创建同一个类的另一个实例。 A copy constructor for class T will always create a T, even if it's passed an instance of a subclass of T. 类T的复制构造函数将始终创建一个T,即使它传递了T的子类的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.