Implementing multiple interfaces

suggest change

A Java class can implement multiple interfaces.

public interface NoiseMaker {
    String noise = "Making Noise"; // interface variables are public static final by default

    String makeNoise(); //interface methods are public abstract by default
}

public interface FoodEater {
    void eat(Food food);
}

public class Cat implements NoiseMaker, FoodEater { 
    @Override
    public String makeNoise() {
        return "meow";
    }

    @Override
    public void eat(Food food) {
        System.out.println("meows appreciatively");
    }
}

Cat must implement the abstract methods from both interfaces. Food is not defined in this snippet, and each public type needs its own source file. A class may implement many interfaces. The class file's interfaces_count is a u2, so the limit is 65,535 (JVMS 4.11).

NoiseMaker noiseMaker = new Cat(); // Valid
FoodEater foodEater = new Cat(); // Valid
Cat cat = new Cat(); // valid

Cat invalid1 = new NoiseMaker(); // Invalid
Cat invalid2 = new FoodEater(); // Invalid

Note:

  1. All variables declared in an interface are public static final
  2. Through Java 7, every method declared in an interface was public abstract. From Java 8, an interface may also declare default and static methods. Default methods have a body and are inherited. Static methods are not abstract and are not inherited. See default methods.
  3. Interfaces cannot be declared final
  4. If two interfaces declare methods with the same name and parameter types, the class implements that method once. There is no way to say which interface it belongs to. Different return types make the two interfaces impossible to implement together.
  5. A corresponding InterfaceName.class file would be generated for each interface, upon compilation

Feedback about page:

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



Table Of Contents