WebReference.com - Part 2 of chapter 5 from Beginning Java 2 SDK 1.4 Edition, Wrox Press Ltd (6/6) | WebReference

WebReference.com - Part 2 of chapter 5 from Beginning Java 2 SDK 1.4 Edition, Wrox Press Ltd (6/6)

To page 1To page 2To page 3To page 4To page 5center
[previous]

Beginning Java 2 SDK 1.4 Edition

Duplicating Objects Using a Constructor

When we were looking at how objects were passed to a method, we came up with a requirement for duplicating an object. The need to produce an identical copy of an object occurs surprisingly often.

Java provides a clone() method, but the details of using it must wait for the next chapter.

Suppose you declare a Sphere object with the following statement:

Sphere eightBall = new Sphere(10.0, 10.0, 0.0);

Later in your program you want to create a new object newBall, which is identical to the object eightBall. If you write:

Sphere newBall = eightBall;

this will compile OK but it won't do what you want. You will remember from our earlier discussion that the variable newBall will reference the same object as eightBall. You will not have a distinct object. The variable newBall, of type Sphere, is created but no constructor is called, so no new object is created.

Of course, you could create newBall by specifying the same arguments to the constructor as you used to create eightBall. In general, however, it may be that eightBall has been modified in some way during execution of the program, so you don't know that its instance variables have the same values--for example, the position might have changed. This presumes that we have some other class methods that alter the instance variables. You could fix this by adding a constructor to the class that will accept an existing Sphere object as an argument:

// Create a sphere from an existing object
Sphere(final Sphere oldSphere) {
  radius = oldSphere.radius;
  xCenter = oldSphere.xCenter;
  yCenter = oldSphere.yCenter;
  zCenter = oldSphere.yCenter;
}

This works by copying the values of the instance variables of the Sphere object, passed as an argument, to the corresponding instance variables of the new object.

Now you can create newBall as a distinct object by writing:

Sphere newBall = new Sphere(eightBall);  // Create a copy of eightBall

To page 1To page 2To page 3To page 4To page 5center
[previous]

Created: July 1, 2002
Revised: July 1, 2002


URL: https://webreference.com/programming/java/beginning/chap5/2/6.html