Implementing an Interface in java
In java, an interface is implemented by a class. The class that implements an interface must provide code for all the methods defined in the interface, otherwise, it must be defined as an abstract class.
The class uses a keyword implements to implement an interface. A class can implement any number of interfaces. When a class wants to implement more than one interface, we use the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.
The following is the syntax for defineing a class that implements an interface.
class className implements InterfaceName{
...
boby-of-the-class
...
}
Let's look at an example code to define a class that implements an interface.
interface Human {
void learn(String str);
void work();
int duration = 10;
}
class Programmer implements Human{
public void learn(String str) {
System.out.println("Learn using " + str);
}
public void work() {
System.out.println("Develop applications");
}
}
public class HumanTest {
public static void main(String[] args) {
Programmer trainee = new Programmer();
trainee.learn("coding");
trainee.work();
}
}
In the above code defines an interface Human that contains two abstract methods learn(), work() and one constant duration. The class Programmer implements the interface. As it implementing the Human interface it must provide the body of all the methods those defined in the Human interface.
Implementing multiple Interfaces
When a class wants to implement more than one interface, we use the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.
The following is the syntax for defineing a class that implements multiple interfaces.
class className implements InterfaceName1, InterfaceName2, ...{
...
boby-of-the-class
...
}
Let's look at an example code to define a class that implements multiple interfaces.
interface Human {
void learn(String str);
void work();
}
interface Recruitment {
boolean screening(int score);
boolean interview(boolean selected);
}
class Programmer implements Human, Recruitment {
public void learn(String str) {
System.out.println("Learn using " + str);
}
public boolean screening(int score) {
System.out.println("Attend screening test");
int thresold = 20;
if(score > thresold)
return true;
return false;
}
public boolean interview(boolean selected) {
System.out.println("Attend interview");
if(selected)
return true;
return false;
}
public void work() {
System.out.println("Develop applications");
}
}
public class HumanTest {
public static void main(String[] args) {
Programmer trainee = new Programmer();
trainee.learn("Coding");
trainee.screening(30);
trainee.interview(true);
trainee.work();
}
}
In the above code defines two interfaces Human and Recruitment, and a class Programmer implements both the interfaces.
When we run the above program, it produce the following output.
In the next tutorial, we will learn about nested interfaces.