Lesson 28 of 34

Inheritance: extends and super

10 min 35 XP

With extends, a child class inherits the parent's fields and methods. super(...) calls the parent constructor. The child can override a parent method to do it its own way.

Example: edit me and press Run

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.

A Java class can extend only one class (no multiple inheritance of classes). Interfaces solve that, coming next.

Challenge

+35 XP

Write class Animal with a String name and a method String sound() returning "...". Dog and Cat extend Animal and override sound() to return "Woof" and "Meow". In main(), read a type (dog/cat) and a name, then print: Input: dog Tommy Output: Tommy says Woof

Output Loading Java (first time takes a few seconds)
Press Run to see the result here.