Inheritance in Java
One base contract, many behaviors, chosen at run time.
Animal[] zoo = { new Dog(), new Cat() };
for (var animal : zoo) {
System.out.println(animal.speak());
}
class Animal {
String speak() { return "..."; }
}
class Dog extends Animal {
@Override
String speak() { return "woof, says the dog"; }
}
class Cat extends Animal {
@Override
String speak() { return "meow, says the cat"; }
}
How it works
extendsinherits;@Overridemarks the replacement honestly.- An
Animal[]holds dogs and cats; each speaks as itself. - The base implementation is the default when nobody overrides.
Keywords and builtins used here
AnimalCatDogclassextendsfornewreturnspeakvar
The run, in numbers
- Lines
- 18
- Characters to type
- 330
- Tokens
- 90
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 60 seconds.
Step 2 of 4 in Classes & records, step 19 of 29 in Language basics.