Reputation: 815
I know Java doesn't support multiple inheritance by not allowing to extend more than one class. I just want to know if there is a workaround for my issue.
I've a class named CustomAction
which needs to extend two abstract classes, BaseAction
and QuoteBaseAction
. I can't change any of these abstract classes and make one extend other.
These abstract classes have method implementations which I need to make use of. I can't create an interface also since an interface can extend only another interface.
Any ideas?
Upvotes: 8
Views: 2610
Reputation: 66226
No, you cannot inherit from two abstract classes. You can work around it if abstract classes implement interfaces. In this case, you can replace inheritance with composition:
abstract class BaseAction implements Action { ... }
abstract class QuoteBaseAction implements QuoteAction { ... }
class CustomAction implements Action, QuoteAction {
private BaseAction baseAction;
private QuoteBaseAction quoteBaseAction;
public Bar methodFromAction() {
return baseAction.methodFromAction();
}
public Foo methodFromQuoteAction() {
return quoteBaseAction.methodFromQuoteAction();
}
}
Upvotes: 1
Reputation: 10260
Your best bet there would be delegation. You could implement both interfaces (if these classes use an interface) or create interfaces to use there and then hold an instance of each class inside your class to which you delegate your calls.
Upvotes: 0
Reputation: 46438
Composition is the way to go.Make one of your abstract class as part of your class.
public abstract class Abs1 {
//
}
public abstract class Abs2 {
//
}
public class Main extends Abs1 {
Abs2 abs2 = ...
//impl
}
Upvotes: 5
Reputation: 4202
Here you go ...
public class CustomAction extends BaseAction {
class Inner extends QuoteBaseAction {
}
}
Upvotes: 5
Reputation: 1661
In java it's possible for abstract classes to extends other abstract classes.
Upvotes: -1