Java Reference
In-Depth Information
Defining Classes
Because you have created classes during each of the previous days, you should be famil-
iar with the basics of their creation at this point. A class is defined via the class key-
word and the name of the class, as in the following example:
class Ticker {
// body of the class
}
By default, classes inherit from the Object class. It's the superclass of all classes in the
Java class hierarchy.
The extends keyword is used to indicate the superclass of a class, as in this example,
which is defined as a subclass of Ticker :
class SportsTicker extends Ticker {
// body of the class
}
Creating Instance and Class Variables
Whenever you create a class, you define behavior that makes the new class different
from its superclass.
This behavior is defined by specifying the variables and methods of the new class. In this
section, you work with three kinds of variables: class variables, instance variables, and
local variables. The subsequent section covers methods.
Defining Instance Variables
On Day 2, “The ABCs of Programming,” you learned how to declare and initialize local
variables, which are variables inside method definitions.
Instance variables are declared and defined in almost the same manner as local variables.
The main difference is their location in the class definition.
Variables are considered instance variables if they are declared outside a method defini-
tion and are not modified by the static keyword.
By programming custom, most instance variables are defined right after the first line of
the class definition, but they could just as permissibly be defined at the end.
Listing 5.1 contains a simple class definition for the class VolcanoRobot , which inherits
from the superclass ScienceRobot .
 
 
Search WWH ::




Custom Search