I have a confusion in why we use abstract classes or interfaces to implement or extend. interfaces doesn’t contain any code so does the abstract methods. then why we use them. why don’t we directly create methods and define them in our class rather we use interfaces or abstract classes. they don’t contain any sort of code, we need to define them after extending them in our class. why we don’t define these methods in our own class rather extend interfaces and then define them. I found such type of question asked several times in stackoverflow but couldn’t understand the answer. can anyone please explain it in some simple way
Share
The power of abstraction and interfaces comes from the fact that you can separate responsibilities and write modular code: One part of your (or someone else’s) code may only care that you have an
Animaland provide facilities to deal with Animals, without needing to know how they move or feed. A different part of your code may only care about defining lots of concrete animals, likeDogs,Birds, etc., with all the details of how they actually implement all their features.By making the concrete classes (Dog, Bird, …) extend a common, abstract interface (Animal), you can use a any now and future concrete class in a library written for the abstract interface — you don’t need to ask the library author to change the library to accommodate new Animals, and the library author doesn’t need to know how features are concretely implemented.
For example, if you had two single algorithm,
FeedBreakfastandFeedDinner, that would require a member functionAnimal::gobble(), then without inheritance you would need to implement each algorithm for each animal – i.e. you’d end up withM * Namount of code! By using a common, abstract interface you reduce this toM + N—Malgorithms andNconcrete classes, and neither side needs to know of the other — they just both need to know the interface.