Chapter 6. Relationships Among Classes
So far, we know how to create a Java class and to create objects, which are instances of a class. But an object by itself isn’t very interesting—no more interesting than, say, a table knife. You can marvel at a table knife’s perfection, but you can’t really do anything with it until you have some other pieces of cutlery and food to use the cutlery on. The same is true of objects and classes in Java: they’re interesting by themselves, but what’s really important comes from relationships that you establish among them.
That’s what we’ll cover in this chapter. In particular, we’ll be looking at several kinds of relationships:
- Inheritance relationships
How a class inherits methods and variables from its parent class
- Interfaces
How to declare that a class supports certain behavior and define a type to refer to that behavior
- Packaging
How to organize objects into logical groups
- Inner classes
A generalization of classes that lets you nest a class definition inside of another class definition
Subclassing and Inheritance
Classes in Java exist in a class
hierarchy. A class in Java can be declared as a
subclass of another class using the
extends keyword. A subclass
inherits
variables and
methods from
its superclass and uses them as if they were
declared within the subclass itself:
class Animal {
float weight;
...
void eat( ) {
...
}
...
}
class Mammal extends Animal {
int heartRate;
// inherits weight
...
void breathe( ) {
...
}
// inherits eat( )
}In this example, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access