Interfaces consists of abstract methods and final variables. Well, it is used as a generalized contract put forth so that classes implementing it should follow the rules by implementing methods in it.
Is this the only use/scope of interface in Java? Have they introduced the concept of interface only for this, or am I missing something? Please help me in understanding the use of interfaces, with examples. (Not on how to use or create interfaces, but to show how they are helping programmers).
Thank you.
The main purpose of interfaces is to act as a guide to programmers who need to implement certain behavior in an implementing class.
For instance, if you were going to implement a Queue class that implements the List interface, the List interface would require that you implement the add method and a remove method, for example.
If your Queue implements the List interface, you must implement your own version of the add and remove methods. The main advantage of using an interface is that you can then interchange one type with another. For instance:
OR
By implementing your class as an interface, you can declare your variables using a more generic type than if you were to use a concrete type. I find this to be really helpful with a bean or data transfer object where one service class might use an ArrayList but another might benefit from using a HashSet. In my bean I can use the interface declaration and let each service class determine what concrete type it wants to use by casting the variable to the concrete type.
Interfaces are basically a way to help standardize things as well as make it easier to swap out one implementing class with another.
I also find that they help me to remember to implement certain methods when I’m programming something, as I can outline them first in the Interface and then the compiler reminds me to implement them.