When should I use interfaces and other times subclasses?
Say a parrot and an human are both a whistler
and they also some animals
but you would have
Code:
class Human extends Animal implements Whistler
Animal - position 1
Whistler - position 2
How do you decide putting which entities at which positions?
thanks
Jack
Re: When should I use interfaces and other times subclasses?
Quote:
Originally Posted by
lucky6969b
How do you decide putting which entities at which positions?
It's Java right?
It doesn't matter from a design standpoint. These are equally fine (assuming you have a choise of making both Animal and Whistler either class or interface):
class Human extends Animal implements Whistler
class Human implements Whistler extends Animal
class Human extends Whistler implements Animal
class Human implements Animal extends Whistler
class Human implements Animal, Whistler
class Human implements Whistler, Animal
They all say the same: Human inherits Animal and Whistler. The difference is implementation convenience only. Class extension allows you to inherit implementation, interface implementation does not.
If you think many/most subclasses will benefit from a shared inherited implementation then you can supply it in a superclass (which is then extended by all subclasses). BUT it's almost always better NOT to inherit implementation at all (because it leads to the brittle superclass problem). You can always work with interfaces only. It's more flexible. Class extension is never needed but may be convenient sometimes (for implementation purposes but never from a design standpoint).