Java Reference
In-Depth Information
Nowthatyouhavetemporarilyfinishedwith
Point
and
Circle
,youwanttotest
their
draw()
methods in a simulated version of the graphics application. To achieve
Listing 2-34.
A
Graphics
class for testing
Point
's and
Circle
's
draw()
methods
class Graphics
{
public static void main(String[] args)
{
Point[] points = new Point[] { new Point(10, 20),
new
Circle(10,
20,
30) };
for (int i = 0; i < points.length; i++)
points[i].draw();
}
}
demonstrated by first having the array's initializer instantiate the
Circle
class, and
then by assigning this instance's reference to the second element in the
points
array.
Movingon,
main()
usesaforlooptocalleach
Point
element's
draw()
method.
Becausethefirstiterationcalls
Point
's
draw()
method,whereastheseconditeration
calls
Circle
's
draw()
method, you observe the following output:
Point drawn at (10, 20)
Circle drawn at (10, 20) with radius 30
How does Java “know” that it must call
Circle
's
draw()
method on the second
loopiteration?Shoulditnotcall
Point
's
draw()
methodbecause
Circle
isbeing
treated as a
Point
thanks to the upcast?
At compile time, the compiler does not know which method to call. All it can do is
verifythatamethodexistsinthesuperclass,andverifythatthemethodcall'sarguments
list and return type match the superclass's method declaration.
Inlieuofknowingwhichmethodtocall,thecompilerinsertsaninstructionintothe
compiledcodethat,atruntime,fetchesanduseswhateverreferenceisin
points[1]
to call the correct
draw()
method. This task is known as
late binding
.