java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.example.fundametal;

public interface RemoteControl {
    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 RemoteControl interface.

package com.javacoderanch.example.fundametal;

public class DummyRemoteControl implements RemoteControl {
    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) {
        RemoteControl 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]);
    }
}