Java Reference
In-Depth Information
16. public void eat(String something) {
17. System.out.println(“Mammal is eating “ + something);
18. }
19. }
The
Mammal
class seems like a typical class with one fi eld, two constructors, and two
public
methods. However, adding the
abstract
keyword to line 1 makes the
Mammal
class
abstract and it cannot be instantiated. The following line of code does not compile:
21. Mammal m = new Mammal();
This statement generates the following compiler error:
Mammal.java:21: Mammal is abstract; cannot be instantiated
Mammal m = new Mammal();
^
So how do we take advantage of this abstract class if we cannot instantiate it? The
answer is to subclass it! A child class of
Mammal
will inherit all the public fi elds and methods
of
Mammal
, as well as the ability to invoke its constructors. The
Mammal
class is still very
useful; we just can't create any instances of it. From a design point of view, this actually
makes sense because no animal is just a mammal. The concept of mammal is abstract in
the real world, so making it abstract in a Java application seems like a good design.
Why Use Abstraction?
The objective of this section is to discuss the details of declaring abstract classes and
abstract methods. The reason for using abstraction is discussed in detail in Chapter 6,
“OO Concepts,” where we revisit our discussion on abstract classes and explain the
benefi ts and usefulness of abstraction in object-oriented programming.
The following
Platypus
class extends
Mammal
. Examine the code, determine if it
compiles successfully, and try to fi gure out the output of running the
main
method:
1. public class Platypus extends Mammal {
2. public int eggCount;
3.
4. public void layEggs() {
5. System.out.println(“Platypus is laying eggs”);
6. }
7.
8. public void eat(String something) {
9. System.out.println(“Platypus is eating “ + something);
10. }
11.
Search WWH ::
Custom Search