Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

158 HOUR 12:Making the Most of Existing Objects


paint()method, implemented by the Componentclass, is passed all the
way down to AnimatedLogo. However, the paint()method does not do
anything. It exists so that subclasses of Componenthave a method they can
use when something must be displayed.
To override a method, you must declare the method in the same way it was
declared in the superclass from which it was inherited. Apublicmethod
must remain public, the value sent back by the method must be the same,
and the number and type of arguments to the method must not change.
The paint()method of the Componentclass begins as follows:
public voidpaint(Graphics g) {

When AnimatedLogooverrides this method, it must begin with a statement
like this:
public voidpaint(Graphics screen) {

The only difference liesin the name of the Graphicsobject, which does not
matter when determining if the methods are created in the same way.
These two statements match because the following things match:

. Both paint()methods are public.
. Both methods return no value, as declared by the use of the void
statement.
. Both have a Graphicsobject as their only argument.


Usingthisandsuperin a Subclass
Twokeywords that are extremely useful in a subclass are thisand super.
As you learnedduring the previous hour, the thiskeyword is used to
refer to the current object. When you’re creating a class and you need to
refer to the specific object created from that class, you can use this, as in
the following statement:
this.title = “Cagney”;

This statement sets the object’s titlevariable to the text “Cagney.”
The superkeyword serves a similar purpose: It refers to the immediate
superclass of the object. You can use superin several different ways:

. To refer to a constructor method of the superclass, as in
super(“Adam”, 12);

Free download pdf