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:
- x is passed as a parameter,
- a variable is initialized to x,
- x is returned as a function value.
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:
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:y = new Robot(x);
If only a bit-wise copy of r is needed, the clone method inheritedfrom the class Object can be invoked inside clone:Object clone(Robot r) { … }
The copy returned by clone can then be cast as a Robot:try { return super.clone(); } catch(CloneNotSupported e) {};
This will raise they =(Robot) x.clone();
CloneNotSupported
exception if Robot doesnot implement the Cloneable interface: Unfortunately, the class Object does not implement Cloneable, hencewe cannot automatically clone an object without going through thehoops described above.class Robotimplements Cloneable { … }
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).