Learn Java · lesson 42 of 61 · about 8 minutes
Inheritance
Add a VIP showing: extend a class to reuse its fields and methods, and override methods to change behaviour.
What you'll learn
- Extend a class
- Call the parent constructor with super
- Override a method
The VIP showing
The cinema adds a late VIP showing of Space Pirates at 22:00: 12 recliner seats, each with free popcorn. A VIP showing is still a showing, with a film, a time and seats left, so rather than copy Showing, the desk writes class VipShowing extends Showing. Its constructor hands the film, time and seats to super(film, time, seatsLeft), then sets the one new field, perk. It also overrides toString(), so System.out.println(vip) prints a whole line about the showing.
Is-a relationships
class Dog extends Animal means every Dog is an Animal: it inherits Animal's fields and methods.
super(name)calls the parent constructor (it must come first)- A method with the same signature overrides the parent's; mark it
@Override protectedfields are visible to subclasses but not to unrelated code
Animal and Dog
class Animal {
protected final String name;
Animal(String name) {
this.name = name;
}
String speak() {
return "...";
}
void introduce() {
System.out.println(name + " says " + speak());
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
@Override
String speak() {
return "Woof";
}
void fetch() {
System.out.println(name + " fetches the ball");
}
}
public class Main {
public static void main(String[] args) {
Dog rex = new Dog("Rex");
rex.introduce();
rex.fetch();
new Animal("Blob").introduce();
}
}Output
Rex says Woof
Rex fetches the ball
Blob says ...Tip
introduce() is written once in Animal, but it calls the overridden speak() for a Dog. That's the start of polymorphism.
Changing what println shows
Every class already extends Object, which has a toString() that prints something like Matinee@1b6d3586. Override it, and println and string joining use your version instead. toString() is public in Object, so the override must be public too.
A matinee that describes itself
class Showing {
String film;
String time;
Showing(String film, String time) {
this.film = film;
this.time = time;
}
}
class Matinee extends Showing {
Matinee(String film) {
super(film, "14:00");
}
@Override
public String toString() {
return film + " matinee at " + time;
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Matinee("Moon Diner"));
}
}Output
Moon Diner matinee at 14:00Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.