chris01
chris01

Reputation: 12321

Java: OOP, multiple extends

                  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

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

Upvotes: 1

Views: 3503

Answers (2)

AlanK
AlanK

Reputation: 9833

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

Upvotes: 5

Joseph Larson
Joseph Larson

Reputation: 9058

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

Upvotes: 0

Related Questions