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");
    }
    public String getName() {
        return "Animal";
    }
}
|  Added class Animal

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

In [3]:
animal.speak();
I am an animal

In [5]:
"I am an " + animal.getName();
|  Expression value is: "I am an Animal"
|    assigned to temporary variable $5 of type String

Out[5]:
I am an Animal
In [6]:
class Dog extends Animal {
    public void speak() {
        printf("woof!\n");
    }    
}
|  Added class Dog

In [21]:
class Cat extends Animal {
    public void speak() {
        printf("meow!\n");
    }    
    
    void poopInBox() {
        printf("wheeew");
    }
}
|  Replaced class Cat
|    Update replaced variable cat, reset to null
|    Update overwrote class Cat

In [22]:
Cat cat = new Cat();
|  Modified variable cat of type Cat with initial value Cat@75412c2f

In [23]:
cat.speak();
meow!

In [24]:
cat.getName();
|  Expression value is: "Animal"
|    assigned to temporary variable $24 of type String

Out[24]:
Animal
In [25]:
dog.getName()
|  Expression value is: "Animal"
|    assigned to temporary variable $25 of type String

Out[25]:
Animal
In [26]:
Dog dog = new Dog();
|  Modified variable dog of type Dog with initial value Dog@73035e27

In [8]:
dog.speak();
woof!

In [27]:
Animal whatisthis = cat;
|  Modified variable whatisthis of type Animal with initial value Cat@75412c2f

In [28]:
whatisthis.speak();
meow!

In [30]:
cat.poopInBox();
wheeew
In [29]:
whatisthis.poopInBox();
|  Error:
|  cannot find symbol
|    symbol:   method poopInBox()
|  whatisthis.poopInBox();
|  ^------------------^

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.