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

(singke) #1
ptg7068951

Establishing Inheritance 157

. The setBackground()method sets the background color of the
applet window.
. The add()method adds user interface components such as buttons
and text fields to the applet.
. The setLayout()method defines how the applet’s graphical user
interface is organized.


The JAppletclass can use all these methods, even though setLayout()is
the only one it didn’t inherit from another class. The equals()method is
defined in Object, setBackground()comes from Component, and add()
comes from Container.


Overriding Methods


Some methods defined in the JAppletclass of objects also are defined in
one of its superclasses. As an example, the update()method is part of both
the JAppletclass and the Componentclass. When a method is defined in a
subclass and its superclass, the subclass method is used. This enables a
subclass to change, replace, or completely wipe out some of the behavior
or attributes of its superclasses. In the case of update(), the purpose is to
wipe out some behavior present in a superclass.


Creating a new method in a subclass to change behavior inherited from a
superclass is called overridingthe method. You need to override a method
any time the inherited behavior produces an undesired result.


Establishing Inheritance


A class is defined as the subclass of another class using the extendsstate-
ment,as in the following:


classAnimatedLogo extendsJApplet {
// behavior and attributes go here
}


The extendsstatement establishes the AnimatedLogoclass of objects as a
subclass of JApplet. As you see during Hour 17, “Creating Interactive Web
Programs,” all Swing applets must be subclasses of JApplet. They need
the functionality this class provides to run when presented on a web page.


One method that AnimatedLogomust override is the paint()method,
which is used to draw everything within the program’s window. The

Free download pdf