Inheritance
Prerequisites: Object-oriented programming: the big picture
A class can extend another class, inheriting its fields and
methods and adding or overriding its own.
class Animal {
String name;
Animal(String name) {
this.name = name;
}
void makeSound() {
System.out.println(name + " makes a sound");
}
}
class Dog extends Animal {
Dog(String name) {
super(name); // calls Animal's constructor
}
@Override
void makeSound() {
System.out.println(name + " barks");
}
}
Dog rex = new Dog("Rex");
rex.makeSound(); // Rex barks
super(name) calls the parent class's constructor — it must be the
first statement in a subclass constructor if used at all.
Common mistakes
- Forgetting
@Overrideon an overriding method. It's not required, but without it a typo'd method name silently creates a brand-new, unrelated method instead of the compiler catching the mistake. - Java only supports single inheritance — a class can
extendonly one other class (though it canimplementmany interfaces).
Practice
Create a Cat class extending Animal that overrides makeSound()
to print "<name> meows".
Show solution
class Cat extends Animal {
Cat(String name) {
super(name);
}
@Override
void makeSound() {
System.out.println(name + " meows");
}
}