The BASE for JAVA LEARNING

by PRO FE S S OR


I N H E R I T A N C E

AN OBJECT-ORIENTED PILLAR


In Object-Oriented Language, INHERITANCE refers to the fact that:
  • attributes and methods of a class (encapsulated part of a program)
  • can use the attributes and methods of another class (the parent class).

    To understand this, let's have an example:

    Let's say that a Vehicle class is the superclass (parent class), and an Automobile class and a Truck class are the descendants of that Vehicle class. (children classes)

    By Inheritance the Automobile class and the Truck class both can use, access and invoked all attributes and methods of the Vehicle class as if they were their own, without having to define them.
    By Inheritance, there is no need to code those methods and attributes again within the descendant classes.

    Ideally, Inheritance should follow the "is a" relationship.

    As you notice, in above example, an Automobile "is a" Vehicle, as well as a Truck "is a" Vehicle.
    The "is a" relationship is followed.


    Why INHERITANCE:

  • Code Re-usability - there is oo need to re-write code nor re-invent the wheel.
  • It improves the usefullness of a class.

  • In JAVA code the 'extends' operator allows a class to inherit from another class.

    See below JAVA code example of Inheritance, using a parent class Vehicle and a child class Automobile.

    class Vehicle
    {

    double mileage;
    private double velocity;
    void speed(double tmpTime)
    {velocity = mileage/tmpTime
    }
    }
    class Automobile extends Vehicle
    { // no need to re-write code for attributes used in the Vehicle class }
    // The Automobile class can use the attributes "mileage" and "velocity" and the method "speed" of the Vehicle class as its own.