Newton
class
and have gone through the tutorial, so you understand what it
does. Now I am going to show you a tiny bit of Java's power.
Our Newton
class is pretty useless -- it only computes
roots of sin! We can extend it though, and override the methods
f
and fprime
to be whatever we want.
In the same directory where you put your Newton.java code, make a file called MyNewton.java and put in it:
class MyNewton extends Newton { static double f(double x) { return x*x-2; } static double fprime(double x) { return 2*x; } }Compile it and run it with an initial guess of 2, just like you did for the
Newton
class. Now you should get an answer
near the square root of two. We have replaced the old sin
function with x*x-2, but we didn't have to worry about the
other contents of the Newton
class.
The key here is in the extends
part of the
declaration. When we say a class extends
another class, our new class gets all the variables and methods
of the old class. In this case, we picked up f
,
fprime
, and main
. What is more,
we are free to add methods, and to override old methods.
In this case, we overrode f
andfprime
.
So our class really contains a main
method, but we
just can't see it.