implements Java Keyword with Examples
The implements keyword is used in a class declaration to indicate that the class being declared provides implementations for all methods declared in the interface whose name follows the implements keyword.
The following example illustrates a class implements an interface and provides a detailed implementation for the interface’s methods:
/**
* This represents payment interface
*/
interface Payment {
public void pay();
}
class CashPayment implements Payment {
// method overriding
@Override
public void pay() {
System.out.println("This is cash payment");
}
}
class CreditPayment implements Payment {
// method overriding
@Override
public void pay() {
System.out.println("This is credit card payment");
}
}
Unlike extends keyword, a class can implement multiple interfaces. The interface names are separated by commas. For example:
interface A {
}
interface B {
}
class C implements A, B {
}
Summary
- A single class may implement multiple interfaces.
- If the implemented class does not provide an implementation for the interface’s methods, the class must be abstract.