java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to implement interfaces in Java?

To implement an interface, a java class must use implements keyword on its class definition. For example, class A implements interface B. The class definition of class A would look like this: class A implements B {}

A class can implements more than one interfaces. For example, class A can implements interface B and interface C: class A implements B, C {}.

Classes that implements an interface must implements all methods declared in that interface.

package com.javacoderanch.example.fundametal;

public interface Language {

    String getBirthday();
    String getGreeting();
    
}

The following class is an English implementation of the Language interface.

package com.javacoderanch.example.fundametal;

public class English implements Language {
    public String getBirthday() {
        return "Happy Birthday";
    }

    public String getGreeting() {
        return "How are you?";
    }
}

The following class is an Indonesian implementation of the Language interface.

package com.javacoderanch.example.fundametal;

public class Indonesian implements Language {
    public String getBirthday() {
        return "Selamat Ulang Tahun";
    }

    public String getGreeting() {
        return "Apa kabar?";
    }
}

And here is a snippet that show the interface and classes in action.

package com.javacoderanch.example.fundametal;

public class LanguageDemo {
    public static void main(String[] args) {
        Language language = new English();
        System.out.println(language.getBirthday());
        System.out.println(language.getGreeting());
        
        language = new Indonesian();
        System.out.println(language.getBirthday());
        System.out.println(language.getGreeting());
    }
}