I had not understood clearly why exactly interfaces are required while I was in college. Put it in different way, I had not seen real applications of interfaces. Now I know the applications of interfaces and I want to help newbies of java to better understand.
The first thing that comes to mind when you hear about interfaces is that why cannot it be done as an “abstract class”(As by definition interfaces are set of abstract methods). Usually new comers to java will be having background of C++ and would have better understood about abstract classes. Let me explain you where and how the interfaces fits in by considering a real world scenario.
Consider you are designing a “Car” object. So what is the hirerchacy of “Car” object? Okay, at top level is “Vehicle”, then it is a “Four Wheeler” as shown below
Note: Do not get confused about what methods will be there in these Classes or what field will be present or how these objects are used. Keep in mind while designing objects the real world entities should be mapped to objects.
Now, a company manufactures a car, say Benz. So Benz car inherts from the “Car” Class,
Suppose Benz car gives a feature of “Auto Drive”. Think a bit how can you model this feature using just inheritance ? Our aim is to show Benz Car has got “Auto Drive” feature to external world. One way to do it is make Benz Car to inhert from both “Car” Class and “Auto Drive” Class (Considering we create a class for “Auto Drive”) . This we cannot do as Java does not support multiple inheritance. Suppose multipule inheritance is supported in Java, would you desing in this way? Think about it, is it good idea to have “Auto Drive” as a class? A class should be mapped to real world entity, “Auto Drive” cannot be an entity but its a feature that any “Car” can provide. Interfaces are applied to model the statement in italics. Define “Auto Drive” as an interface but not as a Class, whoever wishes to provide “Auto Drive” feature would implement this interface i.e., tommorrow “Ford Car” offers “Auto Drive” will implement this interface. Interfaces helps us in having strict hierarchy which in turn leads to better modelling. Now go ahead and read definitions of interfaces and start using it. There are still more applications of interfaces like defining specifications, I do not go in deep and confuse at the first shot.
I hope this entry is easily understandable, if not, post comments. I am happy to clarify but not happy if you leave the page without understanding