0
0
Javaprogramming~5 mins

Why interfaces are used in Java

Choose your learning style9 modes available
Introduction

Interfaces help different parts of a program work together by agreeing on what methods to use. They let us write flexible and organized code.

When you want different classes to share the same methods but have different behaviors.
When you want to separate what a class can do from how it does it.
When you want to write code that can work with many types of objects in a similar way.
When you want to design a system that can be easily extended with new features.
When you want to ensure certain methods are implemented by any class that uses the interface.
Syntax
Java
public interface InterfaceName {
    void method1();
    int method2(String param);
}
Interfaces only declare methods without giving their body (implementation).
Classes that use the interface must provide the method details.
Examples
This interface says any Animal must have a sound() method.
Java
public interface Animal {
    void sound();
}
The Dog class uses the Animal interface and defines the sound() method.
Java
public class Dog implements Animal {
    public void sound() {
        System.out.println("Bark");
    }
}
The Cat class also uses the Animal interface but has a different sound.
Java
public class Cat implements Animal {
    public void sound() {
        System.out.println("Meow");
    }
}
Sample Program

This program shows how two different vehicles use the same interface to start and stop, but each has its own way.

Java
public interface Vehicle {
    void start();
    void stop();
}

public class Car implements Vehicle {
    public void start() {
        System.out.println("Car is starting");
    }
    public void stop() {
        System.out.println("Car is stopping");
    }
}

public class Bike implements Vehicle {
    public void start() {
        System.out.println("Bike is starting");
    }
    public void stop() {
        System.out.println("Bike is stopping");
    }
}

public class Main {
    public static void main(String[] args) {
        Vehicle myCar = new Car();
        Vehicle myBike = new Bike();

        myCar.start();
        myBike.start();

        myCar.stop();
        myBike.stop();
    }
}
OutputSuccess
Important Notes

Interfaces help make your code easier to change and add new features without breaking old code.

One class can use many interfaces, which helps organize different abilities.

Interfaces are like contracts that say what a class must do, but not how.

Summary

Interfaces define a set of methods that classes must implement.

They help different classes work together by sharing common method names.

Using interfaces makes your code flexible and easier to maintain.