Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending multiple classes

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?

like image 941
jijo Avatar asked Mar 15 '13 10:03

jijo


People also ask

Can we extend multiple classes?

You can only Extend a single class. And implement Interfaces from many sources. Extending multiple classes is not available.

Why we Cannot extend multiple classes?

The reason behind this is to prevent ambiguity. Consider a case where class B extends class A and Class C and both class A and C have the same method display(). Now java compiler cannot decide, which display method it should inherit. To prevent such situation, multiple inheritances is not allowed in java.

Can we extend 3 classes from one class?

A class can extend only one class, but implement many interfaces.

How many classes we can extend?

Although classes can inherit only one class, they can implement multiple interfaces.


2 Answers

Here you go ...

public class CustomAction extends BaseAction {
  class Inner extends QuoteBaseAction {

  }
}
like image 163
Sudhanshu Umalkar Avatar answered Nov 14 '22 19:11

Sudhanshu Umalkar


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
 } 
like image 5
PermGenError Avatar answered Nov 14 '22 18:11

PermGenError