×

java · level 2 · unit 5 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

a method to do the same job a new way.

Every animal can speak, but not the same way. Animal has a plain speak, and Dog can override it: write its own speak, with the same name and parameters. Put above it, and Java checks that it really replaces something.

Now a list of Animal can hold dogs and cats. Loop over it, call speak(), and each one answers in its own way. That is : one call, many shapes.

You have done this before! toString and equals came from Object, the superclass of every class, and you overrode them.

import java.util.*;
public class Main {
    static class Animal {
        String speak() { return "..."; }
    }
    static class Dog extends Animal {
        @Override
        String speak() { return "Woof!"; }
    }
    static class Cat extends Animal {
        @Override
        String speak() { return "Meow!"; }
    }
    public static void main(String[] args) {
        List<Animal> pets = List.of(new Dog(), new Cat(), new Animal());
        for (Animal pet : pets) {
            System.out.println(pet.speak());
        }
    }
}

Without @Override, a typo like speek quietly makes a new method instead.