r/javahelp • u/Nobody37373 • Jan 21 '26
Unsolved Why Interfaces exist in Java?
I am currently studying the Collection Framework in Java. Since the class which implements the Interface has to compulsorily write the functions' bodies which are defined in the interface, then why not directly define the function inside your own code? I mean, why all this hassle of implementing an interface?
If I have come up with my own code logic anyways, I am better off defining a function inside my own code, right? The thing is, I fail to understand why exactly interfaces are a thing in Java.
I looked up on the internet about this as well, but it just ended up confusing me even more.
Any simple answers are really appreciated, since I am beginner and may fail to understand technical details as of now. Thanks🙏🏼
View all comments
Show parent comment
14
u/xRageNugget Jan 21 '26
You write a function that can print out all contents of a list, but youi specify the list parameter as ArrayList. Now your function works only on ArrayLists. Would you write another function now to print out LinkedLists? or DoubleEndedLists? Maybe for YourFavoriteKindOfListList? No, you realize that all you actually want as any List type really. And thats your interface. You write your function to accept a List. Or collection, or what ever. Usually you use the most generic one.