Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If you don't clone in Java then what do you do and what do you call it?

Tags:

java

oop

Does anyone have any suggested or established best practices and naming conventions for copy constructors / factory methods etc in Java? In particular, say I have a class Thing and I want a method somewhere that returns a new Thing with the same value as a Thing passed in (or as the instance if it's an instance method). Would you have this as constructor or a static factory method or instance method? What would you call it?

As per the title, I want to avoid clone() and Cloneable.

like image 922
looeeese Avatar asked Jul 06 '09 13:07

looeeese


People also ask

Why do we need cloning in Java?

The clone() method is used to create a copy of an object of a class which implements Cloneable interface. By default, it does field-by-field copy as the Object class doesn't have any idea about the members of the particular class whose objects call this method.

What is clone () in Java?

Object cloning refers to the creation of an exact copy of an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object. Using Assignment Operator to create a copy of the reference variable.

How many ways we can clone in Java?

There are two types of object cloning - shallow cloning, and deep cloning.

What is the difference between clone and copy in Java?

copy: replicate to existing instance (shallow or deep) clone: replicate to new instance (always deep)


2 Answers

Effective Java recommends either of the following:

  1. A copy constructor (as noted by others):

    public Item(Item item)

  2. A copy factory method:

    public static Item newInstance(Item item)

(Also, no copying for immutables)

The primary difference is that with #1 you choose the actual class of the result, and with #2 the implementer can return a subclass. The semantics of the class may guide you into which one is best.

like image 100
Kathy Van Stone Avatar answered Nov 15 '22 18:11

Kathy Van Stone


I would call it a copy method or a copy constructor (as the case may be). If it was a static method, then I would call it a factory.

In terms of what to do, the most flexible and long living option is a copy constructor. This gives subclasses the ability to copy themselves just like the parent.

like image 21
Yishai Avatar answered Nov 15 '22 19:11

Yishai