Interfaces in Programming | OOPs for beginners

This is the second part of my OOPs series, in this article we’ll go over Interfaces.

Let’s get started!

The definition :-

An interface is a programming structure/syntax that allows the computer to enforce certain properties on an object (class).

Let’s take an example,

Say you’re building three classes which are Car, Scooter & Truck. All the three classes would have the method start_engine(), but, every class will have it’s own implementation of “Starting the engine” as Cars, Scooters & Trucks have different methods of starting their respective engines, but the fact that they must have a start_engine method is what the interface ensures. (As every vehicle must have a start_engine() )

What are Interfaces? (Simplified)

  • Interfaces specify what a class must do and not how. It is the blueprint of the class (and a class is the blueprint of the objects)
  • An Interface is about capabilities like a Car may be an interface and any class implementing Car must be able to (or must implement) move(). So it specifies a set of methods that the class has to implement.

In a nutshell, Interfaces are used when you have different classes sharing a common task, but each task is different in it’s implementation.

Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body).

Let’s write some code to understand it better.

interface Vehicle{final int a = 10;// variables// public and abstractvoid start_engine();}
//use the "implements" keyword to implement a particular interfacepublic class Car implements Vehicle 
{
//implementing the function public void start_engine() {// here, write your own implementation of starting the engine of a Car. }


}
  • Helps us achieving total abstraction.
  • Used to achieve loose coupling.

This was it, hope it was helpful in learning OOPs.

Stay tuned, I’ll be posting more articles on OOPs and other topics soon.

Happy Coding! Cheers!

Full-stack software developer 💫❤️| I love good code❤️