Since a class in Java cannot extend multiple classes. How would I be able to get by this?

Bdk Fivehunna picture Bdk Fivehunna · Sep 20, 2012 · Viewed 17.8k times · Source

I have two classes that need to extend one class. I am getting a compiler error since this cannot happen in Java. I know that you can implement as many interfaces you want to in Java but can only extend one other class. How can I fix this problem?

Answer

Jeffrey Blattman picture Jeffrey Blattman · Sep 20, 2012

Use a "has A" relationship instead of "is An".

class A
class B

You (think) you want:

class C extends A, B

Instead, do this:

class C {
  A theA;
  B theB;
}

Multiple inheritance is almost always abused. It's not proper to extend classes just as an easy way to import their data and methods. If you extend a class, it should truly be an "is An" relationship.

For example, suppose you had classes,

class Bank extends Financial
class Calculator

You might do this if you want to use the functions of the Calculator in Bank,

class Bank extends Calculator, Financial

However, a Bank is most definitely NOT a Calculator. A Bank uses a Calculator, but it isn't one itself. Of course, in java, you cannot do that anyway, but there are other languages where you can.

If you don't buy any of that, and if you REALLY wanted the functions of Calculator to be part of Bank's interface, you can do that through Java interfaces.

interface CalculatorIntf {
  int add(int a, int b);
}

class Calculator implements CalculatorInf {
  int add(int a, int b) { return a + b };
}

class Bank extends Financial implements CalculatorIntf
  Calculator c = new Calculator();

  @Override // Method from Calculator interface
  int add(int a, int b) { c.add(a, b); }
}

A class can implement as many interfaces as it wants. Note that this is still technically a "has A" relationship