Abstract Classes Vs Interfaces

Say, we are trying to implement a new behavior 'whistle', to a group of unrelated things.
For e.g.) Assume we are trying to add whistling behavior to parrots, humans, aliens, cookers and a steam engine. Do you find a relationship between these objects? Do these have a is-a or has-a relationship?

 The juice is when we have a group of unrelated objects and you have to define a common behavior between them, Interfaces is the answer. Of course I can write a whistle abstract class and have parrots and humans extend it. The problem is still solved. But does it make sense when Humans and Parrots extend the whistle class just for the sake of implementation?

Imagine you are sitting in a closed room and you hear a whistle sound. At this point, you are not sure who whistles. IT could be parrot or an alien or a human or a cooker. This is another use of interfaces, At run time when you don't know the type of object, it is easier to use an interface and access the behaviors in the object.

I think by now, it is clear to decide between Interfaces and Abstract Classes.

No comments:

Tired of seeing that 500 Bad gateway error while deploying a Springboot application in AWS...?

By default, Spring Boot applications will listen on port 8080. Elastic Beanstalk assumes that the application will listen on port 5000. Th...