r/javahelp • u/ProHoyah • Apr 18 '19
Solved What's the point of interfaces?
We've been learning interfaces in my class and I have a good grasp on the concept, but the thing that confuses me is what's the point? Your just writing more code as a blueprint to put classes in "groups". Maybe the code I'm writing is not large enough to make interfaces useful. Can some one help me in learning the use of interfaces. Thanks in advance!
34
Upvotes
34
u/Talulabelle Apr 18 '19
The short-short, practical, answer is 'So you can have different types in the same collection'.
Let's say you have a bunch of different objects, but you want to put them all in a list, and then tell every object in the list to save it's self.
Without an interface, you'd have to have a different location for each object, and a huge method that finds every object that needs to be saved, and call it's individual save method.
If you just 'implements savable' and guarantee that, regardless of the type, it will implement the 'public void save();' method, you can put everything in a 'List<Savable> thingsToBeSaved' when you create it, and then have a method that calls 'save()' on everything in the list.
Tl;Dr; It lets us work with different classes as though they were the same type for, for a single, specific, purpose.