Implementing an Interface

An interface can be implemented by a class using the implements keyword. Another interface can not implment the interface but can extend it using the extends keyword.

Syntax

The implements keyword should come after the extends keyword if the class inherits from another class. We will discuss inheritance in an upcoming section.

public class ClassName implements InterfaceName{

}

Example Implementation

Here is an example of the Message class implementing the Comparable interface. In this example we have used the default code provide by the IDE but we will need to write code to define how to compare Message classes.

The Comparable interface define one method, compareTo(). Since the Message class implements the interface, it has to provide the implementation for the compareTo method.

Implementing Many Interfaces

A class can implement many interfaces by adding a comma separated list of interface names after the implements keyword.

public class ClassName implements Interface1, Interface2, Interface3 {

}

Example Implementing Many Interfaces

The methods from all the interfaces will need to be implemented. Notice the comma separated list of interfaces(Comparable and List) after the implements keyword.

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class Message implements Comparable, List {
    String id;
    String text;

    @Override
    public int compareTo(Object o) {
        return 0;
    }

    @Override
    public boolean add(Object o) {
        return false;
    }

    @Override
    public boolean remove(Object o) {
        return false;
    }

}

For readability, some methods from the List interface have been removed.

results matching ""

    No results matching ""