Since Java 8, interfaces can have methods with bodies. Before this update, interfaces could only contain abstract methods, which are method signatures without an implementation. Now, methods in an interface can have bodies if they are declared as default
, static
, or (since Java 9) private
.
Default methods
Default methods provide a default implementation for a method directly in an interface. Classes that implement the interface can use this default implementation without having to provide their own, or they can choose to override it.
Purpose: This feature was added primarily for backward compatibility. It allows a developer to add new methods to an existing interface without breaking all the classes that already implement it.
Static methods
Static methods in an interface are associated with the interface itself, not with any specific instance of a class that implements it. They must be called using the interface's name and cannot be overridden by implementing classes.
Purpose: This is useful for grouping utility methods that are related to the interface.
Private methods (Java 9+)
Introduced in Java 9, private methods within an interface are helper methods that can only be called from other methods inside the same interface. They are used to reduce code duplication in
default
or static
methods. Purpose: To refactor code shared between
default
and static
methods without exposing the helper method to implementing classes.
No comments:
Post a Comment