How do I create an interface in Java?

Inteface only contains methods declaration and all its methods are abstract methods. In its most common form, an interface is a group of related methods with empty bodies. To create an interface, use interface keyword in class definition. The file name of interface always the same with the interface name in class definition and the extension is .java.

The RemoteControl interface defines four move methods and a getPosition() methods. These methods has no bodieds. If a class implements an interface, the class should implements all the contracts / methods defined by the interface.

package org.kodejava.example.fundamental;

public interface RemoteController {
    void moveUp(int n);

    void moveRight(int n);

    void moveDown(int n);

    void moveLeft(int n);

    int[] getPosition();
}

The following snippet show you how to create a class that implements the RemoteController interface.

package org.kodejava.example.fundamental;

public class DummyRemoteControl implements RemoteController {
    private int x;
    private int y;

    public DummyRemoteControl(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public void moveUp(int n) {
        x = x + n;
    }

    public void moveRight(int n) {
        y = y + n;
    }

    public void moveDown(int n) {
        x = x - n;
    }

    public void moveLeft(int n) {
        y = y - n;
    }

    public int[] getPosition() {
        return new int[] {x, y};
    }

    public static void main(String[] args) {
        RemoteController control = new DummyRemoteControl(0, 0);
        control.moveDown(10);
        control.moveLeft(5);
        System.out.println("X = " + control.getPosition()[0]);
        System.out.println("Y = " + control.getPosition()[1]);
    }
}
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply