Inheritance

Inheritance is a mechanism where we can inherit all the fields and methods of one class to another. It is an important part of OOPs (Object Oriented programming system). When we inherit from an existing class, we can reuse methods and fields of the parent class. Moreover, we can add new methods and fields in our current class also.

In the above syntax, we can see 2 classes called Class1 and Class2. Class1 is present in the right hand side(RHS) of : and Class2 is present in the left hand side(LHS). This RHS and LHS classes are having multiple names. We'll study what are some other terms used for these classes below

CODE

EG 1 . Creating a class called Rectangle2D and inheriting to Rectangle3D class

class Rectangle2D {
    //Protected members can be only accessed inside its child class.
    protected double length, width;
    public double Area() {
        return length * width;
    }
    public double Perimeter() {
        return 2 * (length+width);
    }
}

//Inheriting Rectangle2D to Rectangle3D
class Rectangle3D : Rectangle2D {
    public double height;
    public double Volume() {
        return length * width * height;
    }
}