java · level 2 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Adult and child tickets. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.*;
public class Main {
static class Ticket {
int price() { return 10; }
}
static class ChildTicket extends Ticket {
@Override
int price() { return 5; }
}
public static void main(String[] args) {
List<Ticket> tickets = List.of(new Ticket(), new ChildTicket(), new ChildTicket());
int total = 0;
for (Ticket ticket : tickets) {
total = total + ticket.price();
}
System.out.println("Total: " + total);
}
}
your turn
Your turn. Teach the cow to speak.
Make Cow override speak on line 11 with a sound of your choice. Then press run, and watch describe use it.
output
press run to see what happens
fix it
The robin forgot how to fly. Fix it!
output
press run to see what happens
- Java says
method does not override or implement a method from a supertypeon line 6. @Overridepromised to replace a method from Bird. Compare the name on line 7 with the one on line 3.- Change
mvoetomoveon line 7, then press run.
nailed it
your classes speak in their own voices. :D
- Override a method by writing it again in the subclass.
@Overrideasks Java to check it really replaces one.- Polymorphism: each object answers the same call its own way.
new words in your collection
- override
- @Override
- polymorphism
This lesson isn’t saved. A free account remembers every lesson you finish.