Additional flags in the format specifier can, among other things, request zero padding (instead of spaces) or
left-justification (the default is right justification).
Formatted output is covered in detail in Chapter 22.
Exercise 1.13: Rewrite the ImprovedFibonacci program using printf instead of println.
1.11. Extending a Class
One of the major benefits of object orientation is the ability to extend, or subclass, the behavior of an existing
class and continue to use code written for the original class when acting on an instance of the subclass. The
original class is known as the superclass. When you extend a class to create a new class, the new extended
class inherits fields and methods of the superclass.
If the subclass does not specifically override the behavior of the superclass, the subclass inherits all the
behavior of its superclass because it inherits the fields and methods of its superclass. In addition, the subclass
can add new fields and methods and so add new behavior.
Consider the Walkman example. The original model had a single jack for one person to listen to the tape.
Later models incorporated two jacks so two people could listen to the same tape. In the object-oriented world,
the two-jack model extends, or is a subclass of, the basic one-jack model. The two-jack model inherits the
characteristics and behavior of the basic model and adds new behavior of its own.
Customers told Sony they wanted to talk to each other while sharing a tape in the two-jack model. Sony
enhanced the two-jack model to include two-way communications so people could chat while listening to
music. The two-way communications model is a subclass of the two-jack model, inherits all its behavior, and
again adds new behavior.
Sony created many other Walkman models. Later models extend the capabilities of the basic modelthey
subclass the basic model and inherit features and behavior from it.
Let's look at an example of extending a class. Here we extend our former Point class to represent a pixel
that might be shown on a screen. The new Pixel class requires a color in addition to x and y coordinates:
class Pixel extends Point {
Color color;
public void clear() {
super.clear();
color = null;
}
}
Pixel extends both the data and behavior of its Point superclass. Pixel extends the data by adding a field
named color. Pixel also extends the behavior of Point by overriding Point's clear method.
Pixel objects can be used by any code designed to work with Point objects. If a method expects a
parameter of type Point, you can hand it a Pixel object and it just works. All the Point code can be used
by anyone with a Pixel in hand. This feature is known as polymorphisma single object like Pixel can have
many ( poly-) forms (-morph) and can be used as both a Pixel object and a Point object.