Java Reference
In-Depth Information
The next statement calls the
intersects()
method from the
line2
object and returns the
Point
object
at the intersection of the two lines,
line1
and
line2
, as part of the argument to the
println()
method
that outputs the point. As you see, you are not obliged to save an object when you create it. Here you just
use it to create the string to be displayed. After the output statement has executed, the intersection point
object is discarded.
You use the
move()
method in the class
Point
to modify the coordinates of the object
end
that you used
to create
line1
. You then get the intersection of the two lines again, this time calling the
intersects()
method from
line1
. The output demonstrates that
line1
is independent of the object
end
, as moving the
point has made no difference to the intersection.
If you change the constructor in the
Line
class to the earlier version that does not create new
Point
ob-
jects to define the line, you can run the example again to see the effect. The output is:
Points created are 0.0, 1.0 and 5.0, 6.0
Lines created are (0.0, 1.0):(5.0, 6.0) and (0.0, 3.0):(3.0, 0.0)
Intersection is 1.0, 2.0
Intersection is 2.0, 1.0
Changing the
end
object now alters the line, so you get a different intersection point for the two lines
after you move the
end
point. This is because the
Line
object,
line1
, contains references to the
Point
objects defined in
main()
, not references to independent
Point
objects.
RECURSION
The methods you have seen so far have been called from within other methods, but a method can also call
itself. A method that calls itself is described as a
recursive method
, and the process is referred to as
recur-
sion
. You can also have indirect recursion where a method A calls another method B, which in turn calls the
method A. Clearly you must include some logic in a recursive method so that it eventually stops calling it-
self if the process is not to continue indefinitely. You can see how this might be done with a simple example.
You can write a method that calculates integer powers of a variable — in other words, evaluate
x
n
, or
x*x...*x
where
x
is multiplied by itself
n
times. You can use the fact that you can obtain
x
n
by multiplying
x
n — 1
by
x
. To put this in terms of a specific example, you can calculate 2
4
as 2
3
multiplied by 2, and you
can get 2
3
by multiplying 2
2
by 2, and 2
2
is produced by multiplying 2
1
by 2.
TRY IT OUT: Calculating Powers
Here is the complete program, including the recursive method
power()
:
public class PowerCalc {
public static void main(String[] args) {
double x = 5.0;