Java Language Declaring and Implementing an Interface

Download Java Language for free

Example

Declaration of an interface using the interface keyword:

public interface Animal {
    String getSound(); // Interface methods are public by default
}

Override Annotation

@Override
public String getSound() {
    // Code goes here...
}

This forces the compiler to check that we are overriding and prevents the program from defining a new method or messing up the method signature.

Interfaces are implemented using the implements keyword.

public class Cat implements Animal {

    @Override 
    public String getSound() {
        return "meow";
    }
}

public class Dog implements Animal {

    @Override
    public String getSound() {
        return "woof";
    }
}

In the example, classes Cat and Dog must define the getSound() method as methods of an interface are inherently abstract (with the exception of default methods).

Using the interfaces

Animal cat = new Cat();
Animal dog = new Dog();

System.out.println(cat.getSound()); // prints "meow"
System.out.println(dog.getSound()); // prints "woof"
Default methods