CHAPTER 6 ■ OBJECT-ORIENTED PROGRAMMING
Methods in Abstract Classes
Abstract classes can include abstract methods. Any class that extends a class with an abstract method
must implement that method. For example, our Mammal class includes an abstract speak() method. Any
class that extends Mammal must implement the speak method, and that implementation must have the
same signature. So, in this case, the implementations must return void and accept no arguments.
Abstract classes can also include regular methods that their descendant classes can use without
needing to implement them. Listing 6-1 shows both kinds of methods within the Mammal class.
Listing 6-1. Methods within an abstract class
package com.apress.java7forabsolutebeginners.examples.animalKingdom;
abstract class Mammal {
// And here's a method for making the sound.
// Each child class must implement it.
abstract void speak();
// All descendant classes can call this and do
// not need to implement their own versions of it
protected void sayWhatIAm() {
System.out.println("I am a mammal");
}
}
That's a trivial method, but it raises an interesting point. Classes that extend the Mammal class might
also have methods with the same signature. Those methods are said to override this method. For
example, the Cat class might have a sayWhatIAm method of its own. Let's suppose it was identical but
printed “I am a cat” to System.out. Then, to use the Mammal class's method, we'd have to use the super
keyword, as shown in Listing 6-2.
■ Note I made the sayWhatIAm() method protected so that only descendants of the Mammal class can say
they're mammals. If it were public, we might have Snake objects saying they're mammals, and that would be
wrong. Being protected forces any overriding methods in descendant classes to also be protected. Consequently,
the sayWhatIAm() method in the Cat class has to be protected. That makes perfect sense, though. If we were to
add Lion and Tiger classes, we would want them to say they are mammals and cats.
Listing 6-2. The Cat class with an overridden sayWhatIAm method
package com.apress.java7forabsolutebeginners.examples.animalKingdom;
class Cat extends Mammal {
// implement the super class's abstract methods