DEV Community

Deva I
Deva I

Posted on

Interface in Java

An interface in Java is a reference type that acts as a blueprint for a class by defining a strict contract of behaviors without specifying how they are implemented.

It is declared using the interface keyword.

It is primarily used to achieve total abstraction and multiple inheritance in Java.

Key Characteristics

Abstract methods: Interface methods by default they are abstract.

Constants: Any variables declared inside are implicitly public static final.

No Instantiation: You cannot create objects directly from an interface.

Keywords: A class uses implements to adopt an interface, while an interface uses extends to inherit another interface.

Code Example

interface DeliveryPartner
{
    void deliverOrder(String restaurant, String customer);
}
Enter fullscreen mode Exit fullscreen mode
class SwiggyDelivery implements DeliveryPartner
{
    public void deliverOrder(String restaurant, String customer)
    {
        System.out.println("Swiggy is delivering food from " + restaurant);
        System.out.println("Customer: " + customer);
    }
}
Enter fullscreen mode Exit fullscreen mode
class ZomatoDelivery implements DeliveryPartner
{
    public void deliverOrder(String restaurant, String customer)
    {
        System.out.println("Zomato is delivering food from " + restaurant);
        System.out.println("Customer: " + customer);
    }
}
Enter fullscreen mode Exit fullscreen mode
public class FoodDeliveryApp
{
    public static void main(String[] args)
    {
        DeliveryPartner partner1 = new SwiggyDelivery();
        partner1.deliverOrder("A2B Restaurant", "Deva");

        System.out.println();

        DeliveryPartner partner2 = new ZomatoDelivery();
        partner2.deliverOrder("Domino's Pizza", "Rahul");
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Top comments (0)