oopinterfaceabstract-class

Can anyone broadly explain abstract class and interface?


Can anyone broadly explain abstract class and interface? I know about those theoretically but I think It's not enough for implementation. I saw a lot of tutorials on those but it seems to me without abstract class I can do my job, so that why I need to use an abstract class. Actually, I want to know what exactly use of abstract and interface and how it'll helpful.


Solution

  • Understanding what these two mechanisms do in programming is a tough one to teach really because on paper they share a lot of similarities, and in code even more so depending on the language. The question you have asked will likely throw up many duplicate references because it is a question that gets asked a lot. But to focus in on the premise for asking I'll see if I can add a bit more context.

    Interfaces

    A way of declaring common related properties and methods between classes. Class definitions can inherit many of these, and it is down to each class that declares inheritance of said interface to implement the members and methods.

    Abstract Classes

    Similar to interfaces, abstract classes declare common related properties and methods, however a class may only inherit one abstract class, which is one of the main defining characteristic (and obvious) differences between the two. Because of that characteristic you will often hear abstract classes referred as a base class (although any class can be a base class as long as it is not sealed or final). Some other language dependent differences include being able to define static, instanced, protected and virtual (can be overridden) methods.

    So as you can see both of these mechanisms have their uses and each has something that the other does not. This means there will be times when one is relevant when the other is not, and times when both are needed in tandem.