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

10

u/Brafaan Apr 05 '22

Abstract class vs interface class, and when to use them and why.

10

u/SavvyPlatinum Apr 06 '22

Put simply.

Interface is just a structure that a class has to follow. The interface might say "a class needs to have an Add method and a Subtract method", but the interface doesn't implement the methods. It allows you to define the name, inputs and output type of methods in the class without implementing them. It's up to the class how to implement it. It's useful if you'd like multiple classes that do the exact same thing but in different ways, then you can use an interface to force them to share the structure.

An abstract class is just a normal class, but you can't instantiate them. You can leave the implementations empty (similar to interface), but you can also implement some methods. If you do, any class that inherits this abstract class will also inherit the implementations. It allows you to share implementation of methods between some classes if you know those implementations will be the same.

A class can both implement an interface and inherit an abstract class at the same time.

Feel free to DM if you'd like it explained in more detail.

1

u/scmbradley Apr 06 '22

In java, if I understand it correctly, you get compile errors if you haven't implemented the methods the interface expects, which seems somewhat useful. But in Go, I don't think there's any of that error checking. So, in go, is an interface just like a code comment ("hey you better implement these methods") but baked into the syntax of the language? (interfaces are also how Go lets you just straight up break any typechecking, but that's another topic...)