Declaring and Implementing an Interface

suggest change

Declaration of an interface using the interface keyword:

public interface Animal {
    String getSound(); // public and abstract 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";
    }
}

Cat and Dog must define getSound() because an interface method is abstract unless it is a default or static method. Two public classes cannot share one source file.

Using the interface

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

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents