Inheritance
Programming Languages · Java Objects · 15 min
Build new classes on top of existing ones and change what they do.
extends
A class can extend another and get all its fields and methods for free. The original is the parent; the new one is the child. The child can add its own extras too.
class Puppy extends Dog {
void wag() {
System.out.println("Wag!");
}
}
Write
class Cat extends Animalwith a methodvoid meow()that printsMeow!In
main, create aCatand calleat(), thenmeow(), on it.
Calling the parent: super
When the parent's constructor needs a value, the child must pass it up with super(...), as the first line of its own constructor.
Puppy(String name) {
super(name); // runs Dog's constructor
}
Write
class Cat extends Animalwith a constructorCat(String name)that callssuper(name).In
main, createnew Cat("Tom")and print itsname.
Overriding a method
A child can override a parent's method: write a method with the same name, and the child's version runs instead. Put @Override above it so Java double-checks the name.
Inside, super.speak() still runs the parent's version if you want both.
@Override
void speak() {
System.out.println("Tweet!");
}
In
Dog, overridespeak()with@Overrideso it printsWoof!Make Dog's
speak()callsuper.speak()first, so both lines print.
A parent-type variable
A Dog is an Animal, so an Animal variable can hold one. When you call a method, Java runs the version of the object actually inside, even through the parent type.
This lets one variable hold different kinds of animals.
Animal a = new Dog();
a.speak(); // Dog's speak runs
Create
Animal pet = new Dog();and callpet.speak().Now put a
Catin the same variable (pet = new Cat();) and callpet.speak()again.
Put it together: the payroll
Every Employee earns 1000 and can describe() themselves. A Manager is an Employee who earns 1500. Notice that describe() calls pay(), so a manager's description will use the manager's pay.
Write
class Manager extends Employeewith a constructor that takes aString nameand callssuper(name).In
Manager, overrideint pay()to return 1500.In
main, make anEmployee[]withnew Employee("Ada")andnew Manager("Grace"). Loop over it and print eachdescribe().
More in Java Objects
Previous: ArrayList and HashMap · Next: Interfaces and Abstract Classes