|
Jul/11
27 Why InterfacesI have been asked this question numerous times. Why interfaces exist in Java. First let me start with the answers I get. 1. Interfaces make you implement multiple inheritance in Java. 2. Make code reusable. 3. They are a contract.
Though you can use interfaces in Java in multiple ways, it's better to adhere to why they were designed. Let's start with something even simpler. How do you define an Object. Objects have state and behavior. To put it simply, interfaces simply take this behavior part to another level. Interfaces essentially represent grouping of behavior. Logical grouping of behavior which makes abstraction easier.
As behavior is identified by methods in a class. Interfaces are identified by a group of one or more methods. Let me clarify it with an example. My name is Rishi and I extend human being abstract class ( Rishi is a human being). What interfaces I implement. Let's see. For all our 100+ employees, I implement Employer interface. For my parents, Son interface. For my 4 year old, Father interface. Father interface extends another interface Parent. Now if you see, each of these interfaces is not just one behavior but grouping of behavior. Like Employer will have paySalary() ( delegated to accounts dept), assignWork(), delegateWork() etc.
|

