typestar

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

  1. extends inherits; @Override marks the replacement honestly.
  2. An Animal[] holds dogs and cats; each speaks as itself.
  3. The base implementation is the default when nobody overrides.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 4 in Classes & records, step 19 of 29 in Language basics.

← Previous Next →

Inheritance in other languages