In Java, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. It defines a contract that classes can implement, specifying a set of methods that implementing classes must provide. Interfaces enable multiple inheritance in Java and are used to achieve abstraction and polymorphism. Here's an overview of Java interfaces:
Declaring Interfaces:
Interfaces are declared using the interface keyword followed by the interface name.
Interface methods are declared without a method body (no implementation).
By default, interface methods are assumed to be public and abstract.
Example of an interface:
public interface Drawable {
void draw(); // Abstract method
}
Implementing Interfaces:
A class implements an interface by providing implementations for all the methods declared in the interface.
A class can implement multiple interfaces, separating them with commas.
Example of implementing an interface:
public class Circle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
Interface Default Methods:
Java 8 introduced default methods, allowing interfaces to have method implementations.
Default methods provide backward compatibility, allowing new methods to be added to interfaces without breaking existing implementations.
Default methods are declared using the default keyword.
Example of a default method in an interface:
public interface Drawable {
void draw(); // Abstract method
default void resize() {
System.out.println("Resizing the shape");
}
}
Interface Static Methods:
Java 8 also introduced static methods in interfaces.
Static methods can be defined in interfaces and called using the interface name.
Example of a static method in an interface:
public interface Drawable {
void draw(); // Abstract method
default void resize() {
System.out.println("Resizing the shape");
}
static void display() {
System.out.println("Displaying the shape");
}
}
Benefits of Interfaces:
Abstraction: Interfaces allow you to define a contract without specifying the implementation details.
Multiple Inheritance: Java interfaces support multiple inheritance, allowing a class to implement multiple interfaces.
Polymorphism: Interfaces enable polymorphism by allowing objects of different classes to be treated interchangeably if they implement the same interface.