| | | Describing similar things |
Describing similar things
Before we answer these questions, we need to consider some new
concepts and their use within Java. Let's start by thinking about how
we describe things in English. We often describe real world objects
as being like something else but then describe what the difference is:
- What is a strobe light? It's a light that flashes. It has an
extra behavior that most lights don't have.
- What is a poisonous snake? It's a snake whose bit is
poisonous. All snakes bite (except probably our friend Nibbles),
so "poisonous" does not describe a new behavior, but a
different effect than that seen from other kinds of snakes
when they bite.
- What is a textbook? It is a book that is used in a course. It
contains questions that can be given out as assignments. It has
properties that most books don't have (questions) that
enable it to be used in ways that most books can't be used.
We'd like to be able to do similar things in Java, and these are
exactly the kinds of things we can do with the keyword extends.
The class we "extend" is the class that we are like. The constants,
variables, and methods that we define indicate how the new class
differs from the one that we are extending.
We have done this all semester to create
WindowControllers and ActiveObjects. For example,
consider the header
public class Fall extends WindowController
from our falling leaves example. Fall is a WindowController. It has the same behaviors and properties as other
WindowControllers, except for the things that we specify: 1) how
it it draws the display (defined in the begin method) and 2) how it
responds to mouse clicks (creating a tree from which leaves fall).
Here, we call Fall the subclass and WindowController the
superclass.
- What is a WindowController?
- A WindowController has a canvas (defines the
canvas instance variable)
- It translates mouse events into onMousePress,
onMouseRelease, etc. method calls
- It extends Controller
Since Fall extends WindowController, Fall also has a canvas instance variable we can use, even though we did not declare
it ourselves. The WindowController also provides the code that
makes sure onMousePress() gets called when we expect. And since
WindowController extends Controller, we know that Fall
implicitly extends Controller.
- What is a Controller?
- It supports the loading of images and sounds (getImage,
getAudio)
- It extends JApplet
So we can call methods getImage and getAudio
because they are defined in Controller.
JApplet is a Java class. Since our Fall class extends JApplet (indirectly), we can also do everything that JApplets can do. There are lots of methods in JApplet (and the
classes it, in turn, extends), but the only one we have really
been using is the getContentPane() method that allows us to add
Swing components to the display.
| | | Describing similar things |