1
                  abstract class CAR
                       fuelUp () { // implemented }
                  /            \
interface SPORTER               interface TRUCK
    driveFast ();                    moveLoad ();

Is there a way in Java I can get a class ESTATE that has

  • the implementation fuelUp of CAR
  • and also must implement driveFast AND moveLoad?

Extending from multiple classes is not possible and making CAR an interface does not give me an implementation in CAR.

Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
chris01
  • 10,921
  • 9
  • 54
  • 93
  • 3
    `class ESTATE extends CAR implements SPORTER, TRUCK` ? – Alan Kavanagh Jul 05 '18 at 12:41
  • In Java 8+ Car can be an interface with a default implementation for `fuelUp()`. – nickb Jul 05 '18 at 12:43
  • 3
    Remember that inheritance isn't a magic bullet meant for solving all problems (in fact it often causes more problems than it solves). In cases like this it's probably not at all the right approach to try to model all car types as their own classes. – Kayaman Jul 05 '18 at 12:43

2 Answers2

5

Your Java class can only extend 1 parent class, but it can implement multiple interfaces

Your class definition would be as follows:

class ESTATE extends CAR implements SPORTER, TRUCK {}

For more help, see: https://stackoverflow.com/a/21263662/4889267

Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
0

As already identified, you can extend one class and implement multiple interfaces. And in Java 8+, those interfaces can have default implementations.

But to add to this, you can also have various implementations of SPORTER, for instance. You could make use of the SporterAlpha implementation through composition.

class Foo extends Car implements Sporter {
    private SporterAlpha sporterAlpha;

    public int sporterMethodA(int arg1) { return sporterAlpha.sporterMethodA(arg1); }
}

Repeat as necessary to expose all the SporterAlpha methods necessary.

Thus, you can:

  • Inherit from no more than one superclass
  • Implement as many interfaces as necessary
  • Use default implementations on your interfaces with Java 8+
  • Use composition as appropriate
Joseph Larson
  • 8,530
  • 1
  • 19
  • 36