The dependency Inversion principle says that (Head First Java):
- Depend upon abstractions. Do not depend upon concrete classes.
What does it mean with respect to inheritance? As a subclass depends on concrete class.
I am asking for a case when say - There is an interface Bird
(doesn't have fly method as some birds cant fly), which represents all Non-Flying Birds. So I create a class - NonFlyingBird
which implements Bird
.
Now I want to make a class for Birds that can fly. As NonFlyingBirds
and FlyingBirds
have the same attributes I extend the FlyingBirds
from NonFlyingBirds
and Implement Flyable
to give it flying behavior.
Do Doesn't it break the dependency Inversion principle as FlyingBirds
is extending from a concrete class NonFlyingBirds
?
interface Bird { // Represents non Flying birds
void getColor();
void getHeight();
...
}
class NonFlyingBird implements Bird {
void getColor();
void getHeight();
...
}
class FlyingBird extends NonFlyingBird implements Flyable { // Does it break Dependency Inversion principle by extending concrete NonFlyingBird class?
Flyable fly;
...
}
Note - The only reason I am extending is because the FlyingBird
has the same attributes and methods as NonFlyingBird
+ the flying behaviour. So it kind of makes sense to reuse code by inheritance.
Aucun commentaire:
Enregistrer un commentaire