Java Reference
In-Depth Information
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
Let's recap what we have learned about methods and constructors with another example.
Using Objects
Let's create an example to do some simple 2D geometry. This will give us an opportunity to use more
than one class. We will define two classes, a class of point objects and a class of line objects - we then
use these to find the point at which the lines intersect. We will call the example TryGeometry , so this
will be the name of the directory or folder in which you should save the program files. Quite a few lines
of code are involved so we will put it together piecemeal, and try to understand how each piece works
as we go.
Search WWH ::




Custom Search