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 Animal with a method void meow() that prints Meow!

  • In main, create a Cat and call eat(), then meow(), 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 Animal with a constructor Cat(String name) that calls super(name).

  • In main, create new Cat("Tom") and print its name.

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, override speak() with @Override so it prints Woof!

  • Make Dog's speak() call super.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 call pet.speak().

  • Now put a Cat in the same variable (pet = new Cat();) and call pet.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 Employee with a constructor that takes a String name and calls super(name).

  • In Manager, override int pay() to return 1500.

  • In main, make an Employee[] with new Employee("Ada") and new Manager("Grace"). Loop over it and print each describe().

More in Java Objects

Previous: ArrayList and HashMap · Next: Interfaces and Abstract Classes