First of all try to understand what is diamond problem?
Consider the below diagram which shows multiple inheritance as Class D
extends both Class B & C. Now lets say we have a method in
class A
and Class B
& C
overrides that method in their own way. Now problem comes here –
Assume, method hello() is overridden in Class B and C.
Class D is extending both B & C, so now if Class D wants to use the same
method i.e. hello(), which method would be called ? the overridden method hello() of B or or C ?. Because of this ambiguity java doesn’t support multiple inheritance.
Also, multiple inheritances does complicate the design and creates problem during casting, constructor chaining etc
and given that there are not many scenario on which you need multiple
inheritance its wise decision to omit it for the sake of simplicity.
Also java avoids this ambiguity by supporting single inheritance with
interfaces. Since interface only have method declaration and doesn't
provide any implementation there will only be just one implementation of
specific method hence there would not be any ambiguity.
No comments:
Post a Comment