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

Show parent comments

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.

1

u/__Fred Apr 06 '22 edited Apr 06 '22

Yes. A lot of OOP is for organizing code, so other people, or yourself in the future can understand it.

You don't need to have OOP to achieve anything technical. The processor doesn't understand what an interface is.


Why don't just use classes with methods that don't do anything?

Because it gives people the option to inherit from another class and still implement the interface. Because you can only ever inherit from one class (e.g. in Java).

Also, it prevents people from trying to create objects from your bare "interface-class" that is only meant to be inherited/implemented.