r/learnprogramming • • 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

738 comments sorted by

View all comments

3

u/[deleted] Apr 05 '22

Interfaces.

I get that it's used for inheritance, but I cant quite wrap my head around when or why you'd need to write one.

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.

4

u/door_of_doom Apr 05 '22

An improvement that I'd like to make to this answer: We generally don't call it inheriting from an interface, we generally refer to it as implimenting an interface.

Cat doesn't inherit the Animal interface, it implements the Animal interface.