Computer Sciences 313e - Inheritance

Example:

class Animal
{
    float weight;
    int numberOfLegs;

    void eat() {...}
    void drink() {...}
    void move() {...}
}

class Dog extends Animal
{
    String breed;
    // inherits weight, numberOfLegs

    void bark() {...}
    // inherits eat(), drink(), move()
}

Dog instances can be used anywhere Animal instances can be used.

Example:
Animal tbone;
tbone = new Dog();
tbone.move(); <--- A Dog instance is also an instance of Animal, so the move() method can be invoked

Overriding Methods in the Parent Class

Example Overriding the move() method from Animal in the Dog class:

class Dog extends Animal
{
    String breed;
    // inherits weight, numberOfLegs

    void bark() {...}
    void move() { // a special version of the move() method just for Dog objects }
    // inherits eat(), drink()
}

Keyword Super

Example

class Dog extends Animal
{
    String breed;
   ...
    void move()
   {
       ...
       super.move(); // Call implementation of move() in superclass Animal
    }
}

Example

class Person
{
    Person(String name)
    { ... }
}

class Doctor extends Person
{
    Doctor(String name, String specialization)
    {
        super(name); // Call the Person constructor and pass in name
        ... // do some other stuff
    }
}