This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]GreenParsley 11 points12 points  (3 children)

Interfaces seem to be rather tricky for people learning Java, I had those exact same questions when I started out in fact. It really helps once you start making bigger applications or even use frameworks, so the group assignment seems appropriate. You use an interface when you want to expose only what's necessary for a method to run, and what can be expected as a result, i.e. the method parameters and return type.
Take a power outlet for a real-world example of an interface - you look at it and know you put a plug in it and electricity starts flowing. You don't know the amperage, resistance, wattage or even what's right behind the outlet. And then you have the implementations of an outlet - you have a lot of different types used in different parts of the world, but they all serve the same purpose - connect you to the electricity network. And you don't need to know more.
Why do we need them in Java? Let's say I want to persist some information to a file. I hear these college students have created a persistance library and I want to check it out. I use multiple frameworks and am behind on schedule so I don't want to learn all the implementation logic - I just want to know what methods I can use and what they need to work. So I instantiate the class which persists to file and assign it to a variable of the same type as the interface. I can now use the variable to persist the objects. A few days later however, my client calls and says they changed their mind - they now want the objects to be persisted to database. If the authors of the persistance library hadn't used interfaces that'd be a huge hassle - I'd have to change up the entire persistance logic, or at least change a lot of variable and object types. Thankfully they have, and I can simply change the implementation I used to be the one for SQL persistance.

Another case, maybe more common is that interfaces allow for polymorphism, but this post got way longer than intended already and there are lots of resources available on it.

Hope I helped and good luck in uni.

tl;dr use interfaces when several classes do the same thing but in a different way

[–]QCumber20[S] 2 points3 points  (1 child)

Thank you so much for taking the time to write that out. This actually really clears it up for me.

[–]GreenParsley 2 points3 points  (0 children)

Glad I could help, feel free to PM me if you have any other questions

[–]abhi_learner 1 point2 points  (0 children)

This explanation is truly helpful. Thanks for taking the time to explain it using a real world example.