Low Orbit Flux Logo 2 F

Java How To Implement An Interface

In Java an interface is similar to a class except that it can’t actually be instantiated. Interfaces have no constructors. They only have “public static final” fields.

Here is an example of the basic syntax for an interface.


interface Test5 {
    void method1();                 
    default void method2() {
        System.out.println( "Testing ..." );
    }   
}

Interface Methods:

Here is a more complete example:


interface Animal {
    void sleep();                                    // must be implemented
    default void eat() {                             // can be implemented but has default
        System.out.println( "Eating ..." );
    }   
    default void drink() {                           // can be implemented but has default
        System.out.println( "Drinking water.\n" );
    }
}
  
class Monkey implements Animal {
    
    public void sleep() {                         // need to implement
        System.out.println( "Sleeping.\n" );
    }
    public void eat() {                           // implement but also call default from interface
        Animal.super.eat();                       // call default from interface
        System.out.println( "... banana.\n" );    // add implementation specific functionality
    }
    public void climb() {                         // define new method not from the interface
        System.out.println( "Climbing.\n" );
    }
  
    public static void main(String args[]) {
        Monkey d = new Monkey();
        d.sleep();
        d.eat();
        d.drink();
        d.climb();
    }
}