3. Inheritance and Derived Class

A class is a software entity that has internal data and a set of methods or functions that act upon that data.

All well and good. But classes have another powerful property, namely 'inheritance'.

Inheritance means that the data and methods of a class are automatically inherited by any other class derived from the original one.

Example

We had a class called 'Box' that was defined as follows

class Box() {
private var width
private var height


  public function Box() {
    var myBox = new Box
  }


  public setHeight(x) {
    myBox.height = x
  }

}

In an object oriented language, it is possible to create another class called a 'derived class' that is based on an existing class - in this case the class called Box. The derived class has all the properties of the 'superclass' (the parent class) and also some data and methods of its own. Another description of a derived class is 'subclass'

Let's consider a class called ColouredBox shown below

class ColouredBox extends Box() {
private var colour



  public function ColouredBox() {
    var colBox = new ColouredBox
  }


  public setColour(x) {
    colBox.colour = x
  }

}

In this example, the original class called Box has been 'extended' into a class called ColouredBox This class has all the properties of Box but also one additional data property called 'colour'. And in order to change the colour of the box, a new method called setColour() has been defined.

Going on with the example, let the main program instantiate an object of class ColouredBox and manipulate it - like so

Main program {
        theBox = ColouredBox()
        
        theBox.setHeight(20)
        theBox.setColour('Red')
       
      }

Notice that the object called theBox is still able to call the setHeight method, even though it is not present in the ColouredBox code above.

This method has been inherited from the superclass called Box.

The code then goes on to set the colour of the new object using its own, specific method(s)..

 

Challenge see if you can find out one extra fact on this topic that we haven't already told you

Click on this link: Inheritance and derived classes

 

Copyright © www.teach-ict.com