Java Interface class example

Java Interface class only allow to declare abstract classes with only mehtod signatures, no code implementations. Any class implements this interface must implements all the methods in this interface. The purpose of an interface:

  1. Java doesn’t allow a class to extend multiple parent classes, so we can use Interface to do multiple inheritances because a Java class can implement multiple interface classes.
  2. To wrap all methods needed in a single class, works like a contract between the interface class and the class implementing it.
  3. It tells you the available functionalities without the need to know how it works in the back. It is like the buttons on are TV remote controller. To use it, you just need to know the functionaltiy of the button but you don’t need to know how it works to remotely control the TV when you press a button.

A Java interface class

public interface Movements {
    /* In an interface class:
     * All methods are are abstract.
     * Only allow method signature, no method body.
     * Any class implements this interface must
     * implements all methods in this interface class.
    public void running();
    public void jumping();
    public void eating();
    public void working();

A class implements the above interface

public class Dog implements Movements {

     * Implementing the required methods:
     * running()
     * jumping()
     * eating()
     * working()
     * You are free to implement any other
     * methods than the above.
    public void running() {
        System.out.println("A dog is running.");

    public void jumping() {
        System.out.println("A dog is jumping.");

    public void eating() {
        System.out.println("A dog is eating.");

    public void working() {
        System.out.println("A dog is working.");
    public static void main(String args[])
        //Initiating a dog object
        Dog d = new Dog();
        //Calls the following methods on d

The output

    A dog is running.
    A dog is jumping.
    A dog is eating.
    A dog is working.

Search within Codexpedia

Custom Search

Search the entire web

Custom Search