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:
- Non-default Methods
- Can’t have a method body inside the interface.
- Need to be defined in whatever class implements them.
- Default methods
- Need to have a method body defined inside the interface.
- Can be implemented / overridden inside a class that implements the interface.
- Original version can still be called when overriding the interface.
- Don’t need to be implemented / overridden.
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();
}
}