Java Reference
In-Depth Information
Compiling this file produces two class files rather than one, as you might expect from
previous projects. Because the source file defines the
Printer
and
SubPrinter
classes,
both are produced by the compiler. Run
SubPrinter
with the Java interpreter to see the
following output:
x is 0, y is 1
I am an instance of the class SubPrinter
CAUTION
Make sure that you run
SubPrinter
with the interpreter rather than
Printer
. The
Printer
class does not have a
main()
method, so it
cannot be run as an application.
A
SubPrinter
object was created, and the
printMe()
method was called in the
main()
method of
SubPrinter
. Because the
SubPrinter
does not define this method, Java looks
for it in the superclasses of
SubPrinter
, starting with
Printer
.
Printer
has a
printMe()
method, so it is executed. Unfortunately, this method does not display the
z
instance vari-
able, as you can see from the preceding output.
To correct the problem, you could override the
printMe()
method of
Printer
in
SubPrinter
, adding a statement to display the
z
instance variable:
void printMe() {
System.out.println(“x is “ + x + “, y is “ + y +
“, z is “ + z);
System.out.println(“I am an instance of the class “ +
this.getClass().getName());
5
}
Calling the Original Method
Usually, there are two reasons why you want to override a method that a superclass
already has implemented:
To replace the definition of that original method completely
n
To augment the original method with additional behavior
n
Overriding a method and giving the method a new definition hides the original method
definition. There are times, however, when behavior should be added to the original defi-
nition instead of replacing it completely, particularly when behavior is duplicated in both
the original method and the method that overrides it. By calling the original method in
the body of the overriding method, you can add only what you need.