Abstraction in OOP: an overview
Abstract classes take inheritance a step further, letting you write general classes whose properties and logic child classes share.
Apprentice · Java · OOP · Updated
In the same way that we classify things into abstract categories or ideas, we can create abstract classifications in the software that we write. This allows us to create general classes that have properties and logic that can be shared.
We have already started to see this idea with inheritance, but abstract classes allow us to take this concept further.
Do it: list the party's special abilities
Before a battle, the game shows each member of the party with their special ability. Every kind of character works out its ability in its own way. Your method doesn't need to know how: it asks each member for its specialAbility(), and each one answers for itself.
The classes are given at the bottom of the file: Character, the general class, with getName() and specialAbility(), and two kinds of character that extend it and override specialAbility():
- a plain
Character's ability is"Standard", - an
Archer's is"Rain of arrows", - a
Wizard's is"Fireball".
The method gets one value:
party: the party's members, aList<Character>. AnArcheris aCharacter, and so is aWizard, so the list can hold any of them.
For example:
List<Character> party = List.of(new Archer("Robin"), new Wizard("Merlin"));
| Member | Kind | Its line |
|---|---|---|
| Robin | Archer | Robin: Rain of arrows |
| Merlin | Wizard | Merlin: Fireball |
So partyLines(party) returns a list of those two lines, in that order.
Your job: write the method partyLines(List<Character> party) so it returns a List<String>.
- Give one line for each member, in the party's order.
- Each line is the member's name, then a colon and a space (
": "), then the member's special ability. - Ask each member for its
specialAbility(); don't check which kind of character it is. - An empty party gives an empty list.
- Leave the three classes as they are.
Practiced live on the lesson page: write the Java right there and check it.