Object Oriented Programming (Inheritance) (Part 2) - spc-computer-society/spc-cs-db GitHub Wiki

5. Inheritance (Part 2)

If you have not, please read the previous part first.

Now, we have the basics of inheritance set up. However, what if the method written by the superclass does not fit our use cases well? Then, we would have to use a technique called overriding. Overriding is changing the code used when using a method from an instance of a subclass. When a method on the subclass object is used, the subclass's code is executed instead of the superclass.

Let's see this code example (in Java):

public class Phone{
  public void call(int number){
    if(!PhoneNumber.isValid(number)){
      return;
    }
    Dispatch.sendCall(number);
  }
}
public class PoliceOnlyPhone extends Phone{
  @Override
  public void call(int number){
    Police.informImmediate();
  }
}

If we decide to test our PoliceOnlyPhone by the code below:

public class Test{
  public static void main(String[] args){
    PoliceOnlyPhone pop = new PoliceOnlyPhone();
    pop.call(0);
  }
}

Only Police.informImmediate() is executed. However, if we do want the superclass's code to run before our own, we can use:

public class LogNumbersPhone extends Phone{
  @Override
  public void call(int num){
    super.call(num);
    System.out.println(num + " is called.");
  }
}

We used the super to refer to the superclass and use the superclass's code. That way, we can run both sections of code within the same method. It is particularly useful when the superclass initializes some piece of data that we want to initialize as well.