1. Inheritance

In OOP, one can also create a class that is based on another class.

  • The parent class is called the superclass
  • The new, child class is called the subclass

In this example, we make a base class Animal to serve as the superclass of a subclass Dog.

We say that a Dog is-a Animal.

For has-a relationships, we make those properties of the class (like has-a name).

In [1]:
class Animal {
    public void speak() {
        printf("I am an animal\n");
|  Added class Animal

In [2]:
Animal animal = new Animal();
|  Added variable animal of type Animal with initial value Animal@44e81672

In [3]:
I am an animal

In [4]:
class Dog extends Animal {
    public void speak() {
|  Added class Dog

In [5]:
Dog dog = new Dog();
|  Added variable dog of type Dog with initial value Dog@2471cca7

In [6]:

In [7]:
Animal whatisthis = dog;
|  Added variable whatisthis of type Animal with initial value Dog@2471cca7

In [8]:

The Dog object gets the message "speak" and it has a method for that.

This is called Polymorphism.

See Page 19 of your textbook for more details.