Interview Questions

Clone Objects Passed Between Classes to Protect Encapsulation

Java Interview Questions for Cloning and Cloneable


(Continued from previous question...)

Clone Objects Passed Between Classes to Protect Encapsulation

It is Java's shallow copy semantics that make cloning-the process of instantiating a new object that is a duplicate of another-of such importance in Java. When an object is passed as a method argument, both the called and the calling methods share references to the same actual instance.1

class GraphPoint {
GraphPoint(Point c, int t) {
center = c;
type = t;
}


static final int CROSSHAIR = 0; static final int DIAMOND = 1;

private Point center; private int type; }

As the GraphPoint constructor merely records a reference to the supplied Point object, it is vulnerable to changes being made to that object by the caller:

void plot_line(GraphPoint[] line, int m, int c) {
Point next = new Point(0, c);

while (next.x < line.length)="" {="" line[next.x]="new" graphpoint(="" next,="" graphpoint.crosshair);="" next.x="" +="1;" next.y="" +="m;" }="">

This does not fill the array with a series of graph points placed on the line y=mx+c but, instead, stacks all the points on top of each other at the position of the last one constructed! All GraphPoint objects simply refer to next's Point instance.

For some classes, it is meaningful for an object to remain associated with the specific instances it had passed to its constructors; where it is not, either the caller is required to pass only distinct instances as arguments:

line[next.x] = new GraphPoint(new Point(
next), GraphPoint.CROSSHAIR);

or the class must take steps to encapsulate itself from modifications affected without:

GraphPoint(Point c, int r) {
center = new Point(c);
radius = r;
}

If resolved within the class, the same problem must be addressed in any mutators also:

void setCenter(Point c) {
center = new Point(c);
}

(Continued on next question...)

Other Interview Questions