Using an Abstract Class Polymorphically

A chief benefit of object-oriented programming is polymorphism. Abstract classes are one way that Java supports polymorphism. That is an issue best left for another topic all to itself. But here, let's look at what is perhaps the most common reason people make abstract classes in the first place: to get flexibility in their design.

Say you have a little Dungeons and Dragons type game where some hero fights monsters. In this adventure, it is possible for the Hero (we'll make him a class) can encounter Serpents or Goblins. Looking at our requirements, we might determine that a Serpent and a Goblin have certain traits in common. They are both monsters. Let's put a capital M on that and make it a class: Monster. ...

Get Java Garage now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.