Java Reference
In-Depth Information
public class CreateSpheres {
public static void main(String[] args) {
System.out.println("Number of objects = " + Sphere.getCount());
Sphere ball = new Sphere(4.0, 0.0, 0.0, 0.0); // Create a sphere
System.out.println("Number of objects = " + ball.getCount());
Sphere globe = new Sphere(12.0, 1.0, 1.0, 1.0); // Create a sphere
System.out.println("Number of objects = " + Sphere.getCount());
Sphere eightBall = new Sphere(10.0, 10.0, 0.0);
Sphere oddBall = new Sphere();
System.out.println("Number of objects = " + Sphere.getCount());
// Output the volume of each sphere
System.out.println("ball volume = " + ball.volume());
System.out.println("globe volume = " + globe.volume());
System.out.println("eightBall volume = " + eightBall.volume());
System.out.println("oddBall volume = " + oddBall.volume());
}
}
Now the program should produce the output:
Number of objects = 0
Number of objects = 1
Number of objects = 2
Number of objects = 4
ball volume = 267.94666666666666
globe volume = 7234.559999999999
eightBall volume = 4.1866666666666665
oddBall volume = 4.1866666666666665
How It Works
When you create a Sphere object, the compiler will select the constructor to use based on the types of
the arguments you have specified. So, the first of the new constructors is applied in the first statement
that we added to main() , as its signature fits with the argument types used. The second statement that
we added clearly selects the last constructor as no arguments are specified. The other additional
statements are there just to generate some output corresponding to the new objects. You can see from
the volumes of eightBall and oddBall that they both are of radius 1.
It is the number and types of the parameters that affect the signature of a method, not the parameter
names. If you wanted a constructor that defined a Sphere object at a point, by specifying the diameter
rather than the radius, you have a problem. You might try to write it as:
// Illegal constructor!!!
// This WON'T WORK because it has the same signature as the original!!!
Sphere(double diameter, double x, double y, double z) {
xCenter = x;
yCenter = y;
zCenter = z;
radius = diameter/2.0;
}
Search WWH ::




Custom Search