How and when to use interface?

🧭 When Should You Use an Interface?

Use an interface when:

  • You want to define a contract without worrying about implementation.
    It tells classes what they must do, not how to do it.
  • You need multiple inheritance of type.
    Since Java doesn’t allow multiple class inheritance, interfaces let classes implement multiple behaviors from different sources.
  • You expect unrelated classes to share a common behavior.
    For example, both a Bird and a Drone might fly(), even though they have no common ancestor.
  • You want to decouple your code.
    Programming to an interface (instead of a concrete class) makes your code easier to extend and test.

🛠️ How to Use an Interface

1. Define the Interface

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

2. Implement It in a Class

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

    public void stop() {
        System.out.println("Car is stopping");
    }
}

3. Use the Interface as a Type

Vehicle v = new Car();
v.start();  // Output: Car is starting

This lets you swap in any Vehicle implementation—like Bike, Bus, or Hovercraft—without changing the surrounding code.

🔄 Interface vs Abstract Class: Quick Glance

FeatureInterfaceAbstract Class
InheritanceMultiple allowedOnly one superclass
ImplementationNo (until Java 8: default/static)Yes
ConstructorNot allowedAllowed
PurposeDefine what to doDefine what and how

Leave a Reply

Your email address will not be published. Required fields are marked *