1. Declaration
To declare an interface in Java, you use the `interface` keyword:public interface MyInterface { // ... contents of the interface }
2. Abstract Method
Traditionally, interfaces were primarily used to declare abstract methods that implementing classes must override:public interface Drawable { void draw(); }Any class that implements this interface must provide an implementation for the `draw()` method:
public class Circle implements Drawable { @Override public void draw() { // ... implementation for drawing a circle } }
3. Default Methods
Java 8 introduced `default` methods, allowing interfaces to provide a default implementation for methods. This is useful for adding new methods to interfaces without breaking existing implementations:public interface Drawable { void draw(); default void clear() { System.out.println("Default clearing"); } }Implementing classes can choose to override the default method or use the provided implementation.
4. Static Methods
Interfaces can have static methods, introduced in Java 8. These methods belong to the interface itself and can't be overridden by implementing classes:public interface UtilInterface { static int add(int a, int b) { return a + b; } }Usage: `int result = UtilInterface.add(5, 3);`
5. Private Methods
Since Java 9, interfaces can have private methods, which are used to break down default methods into smaller, reusable components:public interface Drawable { void draw(); default void enhancedDraw() { prepare(); draw(); } private void prepare() { // ... preparation logic } }Private methods are not visible to implementing classes or external entities.
6. Sealed Interfaces (Java 17 Feature)
Java 17 introduced sealed interfaces, allowing an interface to restrict which classes or interfaces can implement or extend it:public sealed interface Shape permits Circle, Rectangle { // ... contents of the interface }In the above example, only `Circle` and `Rectangle` can implement the `Shape` interface.
7. Implementing Multiple Interfaces
A unique feature of Java interfaces is that a class can implement multiple interfaces, which offers a form of multiple inheritances:public class Circle implements Drawable, Rotatable { // ... implementations of methods from both interfaces }8. Nested Interfaces** Interfaces can be nested within other interfaces or classes:
public interface OuterInterface { interface InnerInterface { // ... contents of the nested interface } }
Java 17 further elevates the power and flexibility of interfaces, making them an indispensable feature in modern Java programming. It's essential for developers to be familiar with these capabilities to architect versatile, resilient, and forward-compatible software solutions in Java.