Does Java Have Equivalent to C++ Copy Constructor?

Question:
I want a copy of an instance not a reference, e.g.(Image). Iknow of the clone method, but not many classes have it. Along those lines,does Java pass objects to methods as references or copies — as to a constructor?

Answer:
I like this question because it raises several interesting issues.

If x and yare Java objects, the assignment x = y merely causes xand y to refer to the same object. For example, altering a member of yalters thecorresponding member of x. In contrast, if x and y are C++ objects, the assignment x = y assigns to x a copy of y made either by thedefault member-wise copy algorithm, or by a user-defined operator=method. Thus, altering a member of y has no effect on the correspondingmember of x.

Copies of a C++ object, x, will also be made when:

  1. x is passed as a parameter,
  2. a variable is initialized to x,
  3. x is returned as a function value.
In each case, the copy is made by either the defaultmember-wise copy algorithm or a user-defined copy constructor (i.e.a constructor that takes x as a parameter).

By contrast, if x is a Java object, x will be passed by referenceto any function. This means the function’s formal parameter will be merelyan alias for x. To put it another way, Java functions (methods) don’tget private copies of their object parameters like their C++ counterpartsdo. (They get private copies of their non-object parameters, though.)

If x is an instance of a class that has a copy constructor, this can beused to initialize variables in the style of C++. For example, assume xand y are instances of class Robot, then we copy x into y with:

y = new Robot(x); 
If the class Robot doesn’t have a copy constructor, we can copy x into yif the class Robot specifically provides some other copy method. Onetechnique is to provide a method called clone that returns an Object:
Object clone(Robot r) { … } 
If only a bit-wise copy of r is needed, the clone method inheritedfrom the class Object can be invoked inside clone:
try {   return super.clone();  } catch(CloneNotSupported e) {}; 
The copy returned by clone can then be cast as a Robot:
y =(Robot) x.clone(); 
This will raise the CloneNotSupported exception if Robot doesnot implement the Cloneable interface:
class Robotimplements Cloneable { … } 
Unfortunately, the class Object does not implement Cloneable, hencewe cannot automatically clone an object without going through thehoops described above.

In short, if you want to copy an instance of a class that doesn’tprovide a copy constructor or a specific method for copying, you need to create a subclass that either provides a copymethod implemented by you, or implements Cloneable andprovides a clone method that invokes the bitwise super.clone()(or overrides it with your algorithm).

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: