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

4.Inheritance (Part 1)

When you look up object-oriented programming, you often come across this term inheritance. Inheritance is a way to facilitate code reuse. No one wants to write the same code many times, and inheritance reduces repeated code by allowing classes to extend a class. By extending a class,the extending class gets all the methods and properties/fields of the class being extended. This allows code written in another related class to be reused, i.e. inherited. The class being extended is the superclass, and the class extending is the subclass.

Lets see the following code example (in Java):

public class Phone{
  public void call(int number){
    if(!PhoneNumber.isValid(number)){
      return;
    }
    Dispatch.sendCall(number);
  }
}
public class GamingPhone extends Phone{
  public void playGame(String name){
    App.tryUse(name);
  }
}

Now, if we try to do the following:

public class Test{
  public static void main(String[] args){
    GamingPhone gamers = new GamingPhone();
    gamers.call(30624700);
  }
}

Think for a moment. Do you think this works?

When we inherit from a class, we can think of it in terms of a is-a relationship. A gaming phone is a phone, so we should be able to call from it.

This is indeed the case, and this code compiles. We can see that a subclass can also use methods declared in the superclass.

Notes:

Note that in most programming languages, static methods are not part of any object and thus cannot be inherited. You should explicitly use them instead.