Interfaces vs Classes in OOP
So friends, today I have decided to make it easy for those starting their programming courses in Object Oriented programming languages.
Just like the name suggests, Object Oriented Programming (shortened as OOP), is programming in some modular like manner. The module here referring to a complete set of code handling a certain task to completion. As a result, a program is usually broken down into very fine units. Each unit solving a certain task. The units are termed as objects.
When I started programming in OOP, I found it very challenging to differentiate between a class and an interface. It took me time to understand a very basic concept of an interface. Now, a class, just like its name is a collection of objects. Collection here referring to grouping.
The class contains methods, variables and other data structures. It contains the actual implementation of these objects. It implements methods and uses the variables.
An interface on the other hand may contain all that a class contains but does not do implementation. “Does not do implementation”. That is the difference. That is what took me ages to understand. Lucky you courtesy of me.
So the difference between a class and an interface is that the interface does not do any implementation of the objects it contains. It only declares them for use. Lets look at the following example.
interface Me {
gender: string,
age: number,
name: string,
commingHomeSoon()
}
class Me {
gender: string;
age: number;
name: string;
commingHomeSoon() {
// …..Your code comes here
}
}
Both have the same content. One is an interface while another is a class. The class implements the method commingHomeSoon() while the interface is not.
Thanks guys and have a good learning.