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.

2

u/Brafaan Apr 06 '22

Thanks so much, I really appreciate the answer! In C# 8, interfaces can have default implementations, so for me, its the same as an abstract class? Or is the main difference that an interface forces you to implement all its methods, where you dont have to use all from an abstract class?

Do you have an example of where to use them in a real life scenario? Like why an abstract class over a normal parent class? Why an interface instead of an abstract class?

→ More replies (7)