← Java from Scratch
Lesson 41 of 88 · 10 XP
The super keyword
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
super refers to the parent:
class Animal {
String name;
Animal(String name) { this.name = name; }
String describe() { return name + " is an animal"; }
}
class Cat extends Animal {
Cat(String name) {
super(name); // 1. the parent's constructor
}
@Override
String describe() {
return super.describe() + ", it purrs"; // 2. the parent's version of the method + your own part
}
}
If you don't write super(...) in a subclass's constructor, Java inserts super() with no arguments by itself —
and if the parent has no such constructor, you get the error constructor Animal in class Animal cannot be applied.
Task. There's an Item (a title, a price, String info()). Finish Weapon extends Item with damage: its
info() = the parent's info() + , damage N, and a weapon's price is increased by 10% when it's created (an integer, through
super with the recalculated price).
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.