To me, a distinction between an abstract class and an interface is that the abstract class tends to represent a noun while the interface tends to represent a verb. The most famous abstract class is Object, as nounish as it gets. Comparable, on the other hand, derives from "compare" which is a verb. We have seen other verb interfaces such as Locatable from the MBS. There are various listeners; listen being the verb. I'm not sure if the noun/verb --> abstract class/interface distinction is consistently applied, but it does seem to be how a lot of Java coding is done in the materials we see.
What makes a good candidate for an abstract class? A generic noun that is going to be used by multiple subclasses. "Animal" seems like a good example. While you can argue that it could make sense to create instances of Animals, I submit that in a practical sense, it makes more sense to create instances of specific animals. So, it seems reasonable to ponder:
abstract class Animal { ... } class Cow extends Animal { ... } class Cat extends Animal { ... } class Dog extends Animal { ... } etc.So what might the abstract class contain? Pretty much anything a normal class does. It also can contain abstract methods which behave like the methods of interfaces. Here is a tiny piece of what we might expect from the Animal class:
public abstract class Animal { private int eyes; public Animal() { eyes = 2; // typical default number of eyes } public Animal(int eyes) { this.eyes = eyes; } public abstract void talk(); public int numEyes() { return eyes; } }
Since most animals have two eyes, it makes sense to use the default constructor in most cases. However, if we wish to have a 5-eyed animal, it would be good for a subclass constructor to call super(5).
For example, a Cow class could look like this:
public class Cow extends Animal { public Cow() { } public Cow(int eyes) { // mutant cow super(3); } public void talk() { System.out.println("Moo."); } }
Exercise