Inheritance Examples

Contact Us or call 1-877-932-8228
Inheritance Examples

Inheritance Examples

Say you were creating an arcade game, with a number of different types of beings that might appear - wizards, trolls, ogres, princesses (or princes), frogs, etc. All of these entities would have some things in common, such as a name, movement, ability to add/subtract from the player's energy - this could be coded in a base class Entity.

For entities that can be chosen and controlled by a player (as opposed to those that merely appear during the course of the game but can't be chosen as a character) a new class Playable could extend Entity by adding the control features.

Then, each individual type of entity would have its own special characteristics; those that can be played would extend Playable, the rest would simply extend Entity.

you could then create an array that stored Entity objects, and fill it with randomly created objects of the specific classes. For example, your code could generate a random number between 0 and 1; if it is between 0.0 and 0.2, create a Wizard, 0.2 - 0.4 a Prince, etc.

Arcade Game Inheritance

The Java API is a set of classes that make extensive use of inheritance. One of the classes used in the GUI is Window; its family tree looks like this:

Inheritance in Java GUI Classes