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());
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
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
Hello Julian, thank you for visiting my blog and I am glad that the post helpful to you.