DonX
DonX

Reputation: 16379

option for inheritance

Whats the other option we can use for multiple inheritance other than implementing interface

Upvotes: 2

Views: 511

Answers (4)

maxnk
maxnk

Reputation: 5745

At first, it's better to avoid multiple inheritance and use interfaces. And Java actually does not support multiple inheritance.

But you can use mixins to fake the multiple inheritance. There are some manuals about this:

Multiple Inheritance in Java

The Java Mixin Pattern, or Faking Multiple Inheritance

And if you want to make something composite, I advise to take a look at the Qi4j framework:

Composite Oriented Programming with Qi4j

Upvotes: 1

bradheintz
bradheintz

Reputation: 3152

You'll probably have to use composition - i.e., having an instance of your "parent" class as a member of your "child" class. ("Parent" and "child" here indicate the relationship the two classes would have if you were using inheritance.) The containing ("child") class must then wrap the interface of the contained ("parent") class to expose any functionality of the contained class

One way to smooth the wrapping process is to have both the contained and containing class implement the same interface - the implementations of the methods of this interface in the containing class can then be straight calls to the same methods on the contained class.

Upvotes: 0

coobird
coobird

Reputation: 161042

Java does not have multiple inheritance.

From the Interfaces page of The Java Tutorials:

The Java programming language does not permit multiple inheritance ... , but interfaces provide an alternative.

Since multiple interfaces can be implemented by a class, that can be used as a substitution or alternative to having actual multiple inheritance in Java.

Upvotes: 0

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

A direct answer is to use inner classes. That gives you two (or more) objects that are intimately linked but cover independent base classes.

In general, prefer composition over inheritance. It's a common mistake to use inheritance everywhere. However, that leaves inflexible solutions that are difficult to follow.

Upvotes: 3

Related Questions