How do I 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 org.kodejava.basic;

public interface Language {

    String getBirthday();
    String getGreeting();

}

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

package org.kodejava.basic;

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 org.kodejava.basic;

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 org.kodejava.basic;

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());
    }
}
Wayan

2 Comments

  1. Hi Wayan,

    I watched about 10 tutorials about interfaces. None of them could really help me. But finally I found your blog. Your explanation is the first I could really understand. Thank you so much and keep up the good work.

    Greetings from Germany, Bochum

    Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.