Introduction to Inheritance: an overview

Inheritance is an is-a relationship, where a child class such as Archer gets all the variables and methods of its parent class, Character, and adds its own.

Apprentice · Java · OOP · Updated

By

Inheritance is the second pillar in object-oriented programming. It provides an elegant solution to the duplicate-code problem from the DRY Code lesson.

Inheritance defines an Is-A relationship. For instance, one class can inherit from another class, and it inherits all the variables and methods defined by the parent class.

Archer inherits from Character

Since an archer is a character, it inherits all of its variables. An archer has a name, health, level, and experience. But the archer class defines one new variable: arrows.

The archer also inherits all the character’s methods. An archer can attack(), takeDamage(), levelUp(), and has specialAbility(). But an archer can also do something no other character can: it can addArrow(), which lets it attack more powerfully.

Cheat sheets