← Java from Scratch
Lesson 43 of 88 · 10 XP
Abstraction
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
An abstract class can't be created with new — only its subclasses can. An abstract method has no body,
and a subclass must write it:
abstract class Enemy {
protected String name;
Enemy(String name) { this.name = name; }
abstract int damage(); // the what is known, the how is decided by the subclass
void attack() { // an ordinary method is allowed too
System.out.println(name + " hits for " + damage());
}
}
class Orc extends Enemy {
Orc() { super("Orc"); }
@Override int damage() { return 12; }
}
new Enemy("?"); // error: Enemy is abstract; cannot be instantiated
If you forget damage() in a subclass, you get the error Orc is not abstract and does not override abstract method damage().
Task. Finish the subclasses of the abstract Employee: Manager (the base salary + 20%) and Intern (half the base salary).
The program prints the salaries and the total payroll.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.