r/learnprogramming • u/Temporary-Warthog250 • Apr 05 '22
Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them
Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.
Someone else who reads yours and does understand it, try to explain it to them to help them learn
1.6k
Upvotes
5
u/CatatonicMan Apr 05 '22
Interfaces are effectively a contract that tells you what a thing does (at minimum). They allow old code to use new code.
Say I have an Animal interface that defines a method Eat - I'm making a guarantee that all Animals can Eat, and that calling Eat on an Animal - any Animal - is a valid thing to do. If it can't Eat, it's not an Animal.
If I later create a Cat that inherits from Animal, I know the Cat can Eat, because it's an Animal and Animals can Eat.
The crucial bit is that I can write code that takes an Animal - Feed(Animal), say - and that code will work on anything that inherits from the Animal interface.
I can Feed(Cat) because Cat is an Animal. I don't need to know anything more about the Cat. I can Feed(Dog), because Dog is an Animal, too. Feed(Snake). Feed(Tortoise). Feed(Alpaca).
Years later, someone I've never met can make their own Animal (Lobster) and my code will have no problems working with it.