Java Reference
In-Depth Information
void calculateDaysPlayed(int month) {
// Perform implementation here
throw new UnsupportedOperationException("Not
supported yet.");
}
}
As you can see, the
TeamSchedule
class can use all the fields and methods that
are contained within the
abstract Schedule
class. It also implements the
ab-
stract
method that is contained within the
Schedule
class.
How It Works
Abstract classes are labeled as such, and they contain field declarations and methods
that can be used within subclasses. What makes them different from a regular class?
Abstract classes can contain
abstract
methods, which are method declarations with
no implementation. The solution to this recipe contains an
abstract
method named
calculateDaysPlayed()
. Abstract classes may or may not contain
abstract
methods. They can contain fields and fully implemented methods as well. Abstract
classes cannot be instantiated; other classes can only extend them. When a class ex-
tends an
abstract
class, it gains all the fields and functionality of the
abstract
class. However, any
abstract
methods that are declared within the
abstract
class
must be implemented by the subclass.
You may wonder why the
abstract
class wouldn't just contain the implementa-
tion of the method so that it was available for all its subclasses to use. If you think
about the concept, it makes perfect sense. One type of object may perform a task differ-
ently from another. Using an
abstract
method forces the class that is extending the
abstract
class to implement it, but it allows the ability to customize how it is imple-
mented.
5-14. Increasing Class Encapsulation