Interfaces in practice | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Interfaces in practice

What is the use of interfaces in practice? And why? I can’t understand why its good for me. Please show me some example!

25th Apr 2018, 1:32 PM
Zsolt Kelemen
Zsolt Kelemen - avatar
4 Answers
+ 6
If you can sit on an object, it is a chair. a chair might be a table, a piece of wood, a pincushion or a drum... right? ok... sit down on pincushion should be handled a different way than sit down on a table. subclasses of chair? nop doesnt really fit. table&co implement interface chair as they can serve as that. The interface might consist of method sitDown()
25th Apr 2018, 1:51 PM
Oma Falk
Oma Falk - avatar
+ 4
Some objects may share similar behaviours, but might not share the same parent class. Think of a wall and a glass bottle. Chances are their base class is different, but they're both breakable. Therefore they could both implement an IBreakable interface. Just keep coding, eventually you will find an instance where it makes sense to use an interface.
25th Apr 2018, 3:35 PM
Bagshot - avatar
+ 1
The word interface is a clue. It is used to force a particular set of member functions to be implemented. If I wanted your code to 'talk' or more accurately 'interface' with my code, I could force your class to implement the member functions by name, return type and argument list (but not functionality. A written specification would define that).
25th Apr 2018, 5:52 PM
Thanks you! All of you have written great examples. I'm closer to understanding, but now I have to start experimenting. I'd love to see real code snippets 😉
25th Apr 2018, 6:59 PM
Zsolt Kelemen
Zsolt Kelemen - avatar