Java Facts: Multiple Inheritance

“Does Java Support Multiple Inheritance?” This is one of the most favorite java interview questions.

Whenever this question is asked the most common (and sometimes expected) answers are:

“No” or

“Well! Java does support multiple inheritance but with the interfaces not the classes.”

Both the answers are correct and accepted.

However we can find a better answer of the same question if we go by what the Java Specification has to say:

Classes support single implementation inheritance, in which the implementation

of each class is derived from that of a single superclass, and ultimately from

the class Object.”

“Multiple interface inheritance is supported.”

The term ‘implementation inheritance’ may be confused with the keyword implements, which is incorrect. Implementation inheritance means a class can inherit (using the keyword extends) only one super class.e.g.

Incorrect: public class Derived extends Base1, Base2

Correct:  public class Derived extends Base

On the other hand Interface Inheritance implies that a class can implement multiple interfaces (using implements keyword) and an interface can extend multiple interfaces (using extends keyword).

Correct: public class Concrete implements A, B

Correct: public interface C extends A, B

Incorrect: public interface C implements A, B

The concept of inheritance differs from that of C++ in order to avoid the classic diamond problem in C++.

Enjoy Learning,
Kamlesh

Advertisements

2 thoughts on “Java Facts: Multiple Inheritance

    • Thanks Ganesh! I will keep that in mind for sure and try to work in that direction too… (interviews preparation)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s