Implementing multiple interfaces
suggest changeA 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:
- All variables declared in an interface are
public static final - Through Java 7, every method declared in an interface was
public abstract. From Java 8, an interface may also declaredefaultandstaticmethods. Default methods have a body and are inherited. Static methods are not abstract and are not inherited. See default methods. - Interfaces cannot be declared
final - 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.
- A corresponding InterfaceName.class file would be generated for each interface, upon compilation
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents