How do I create an interface in Java?

Interface 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 have no bodies. If a class implements an interface, the class should implement all the contracts / methods defined by the interface.

package org.kodejava.basic;

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.basic;

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

    public DummyRemoteControl(int x, int y) {
        this.x = x;
        this.y = 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]);
    }

    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};
    }
}
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.