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

6. Inheritance (Part 4)

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

There are several problems that may arise from inheritance, and one of the most famous is the Diamond problem. The diamond problem is a problem which arises from ambiguity. Consider the following:

public class A{
  public abstract int a();
}
public class B extends A{
  @Override
  public int a(){
    return 1;
  }
}
public class C extends A{
  @Override
  public int a(){
    return 2;
  }
}
public class D extends B,C{
}

What does new D().a() output?

Most likely, the answer will not be the one you expect, even for different programming languages. Therefore, some languages have disabled inheriting from multiple classes, or so-called multiple inheritance.

To replace this feature, some languages have introduced a construct call an interface. An interface usually only contains abstract methods which are intended to be overridden. Implementing multiple different interfaces are safer because the interfaces contain no code. There will be less ambiguity as the programmer can specifically override the method. The behaviour of the method call of an object will be clear as there is only 1 code block for this method at the same time (the one written in the implementing class).