Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 863
Bdk Fivehunna Avatar asked Feb 20 '23 02:02

Bdk Fivehunna


2 Answers

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

like image 101
Jeffrey Blattman Avatar answered Apr 26 '23 16:04

Jeffrey Blattman


"Two classes that extend one class" is legal.

"One class extending two classes" is against the specification of the language. If you do not want to consider interfaces, it cannot be done.

like image 29
SJuan76 Avatar answered Apr 26 '23 17:04

SJuan76