The Coder's Handbook   

Abstract Classes


Drawing An Animal

Imagine if I asked you to draw a dog.  Some of you might struggle and produce artwork that resembles terrifying nightmare fuel, but you could at least summon an image to your mind.  How about a Cat?  A Fish?  Cool.

What if I asked you to draw a generic Animal.  Not any specific animal, not one of your choice, and not one with the properties of any animal.  

It has an undefined number of legs, a color property but no defined color.  It neither has fur nor does not have fur.  It has a weight and height, but that is also uknown.

You simply can't do it!  You may have noticed in our programs we often make classes that are never actually instantiated into an object.  These are called Abstract Classes.


Making An Abstract Class

Making a class abstract is really simple.  You just add one word to its definition:

abstract public class Animal

Doing this means that now it is impossible to create an Animal elsewhere in your program.  This class does one thing only:  serves as a superclass that you can extend elsewhere.

This provides a simple check to make it clear in your code that trying to make a generic Animal is always a mistake.  But it also unlocks a new power:  the ability to write abstract methods.


Making a Promise

When you're writing an abstract class you will encounter methods that you know most subclasses will need to perform.  For our animal example, this might be walk() or eat().

You will frequently be met with a choice:  do I write a method to provide some sort of default behavior, or make an abstract method and ask the subclass to always define it.

Option #1 - Default Method

I could write some code that simply does nothing.  If an animal doesn't explain how it eats, it simply calls my useless code.

public void eat()




This seems silly.  When we really have no behavior to define, we instead can write an abstract method.

Option #2 - Abstract Method

We won't define what eating does here, but we promise our subclasses will write an eat() method.

abstract public void eat();

This is really powerful.  It means that code that calls the abstract class can use the eat() method freely!  

We just have to make sure to write it in the subclasses.  Fortunately, writing this code allows the compiler to force you to write it.  You won't even be able to run a subclass until you write an eat() method.

Imagine an abstract class like this skyscraper. 

The lower finished floors are data and full methods.

The upper framing are the abstract methods.


Coding With John - Abstract Classes

Alex Lee - Abstract Classes in Java