Interfaces in Programming | OOPs for beginners

Madhavam Pratap Shahi
2 min readJul 27, 2021

--

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.

Declaring an interface in java-

interface Vehicle{final int a = 10;// variables// public and abstractvoid start_engine();}

Implementing the declared interface-

//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. }


}

But why do we use interfaces when the classes can get the job done too?

  • 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!

--

--

Madhavam Pratap Shahi

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