Interface defines a contract that classes can implement. They allow you to specify methods that a class must implement without dictating how these methods should be implemented.
It is a fully abstract class.
Interface contains only
- Constants
- Method signatures (no method body. No braces. Terminated with a semicolon)
- Default methods
- Static Methods
- Nested Types
Interfaces cannot be instantiated, they can only be implemented by classes or extended by other interfaces.
Declare Interface : Uses interface
keyword.
public interface InterfaceName {
// constant fields
// method signatures
// default methods
// static methods
// nested types
}
Abstract Methods: Methods in an interface are abstract by default. They do not have a body and must be implemented by classes that implement the interface.
Constants: Fields declared in an interface are implicitly public
, static
, and final
. They must be initialized at the time of declaration.
Default Methods (Java 8 and above): Methods with a default implementation. Allow interfaces to provide additional functionality without breaking existing implementations.
Static Methods (Java 8 and above): Methods that belong to the interface and not to any instance of the class. Can have a body and can be called on the interface itself.
Nested Types: Interfaces can contain nested types, such as other interfaces or classes.
Example of Declaring an Interface
Let’s consider an interface that defines behaviors for different types of vehicles.
javaCopy code
// Declaring an interface named Vehicle
public interface Vehicle {
// Constant field
int MAX_SPEED = 120; // implicitly public, static, and final
// Abstract method
void start();
// Abstract method
void stop();
// Default method
default void honk() {
System.out.println("Honking the horn!");
}
// Static method
static void displayMaxSpeed() {
System.out.println("The maximum speed is " + MAX_SPEED + " km/h.");
}
// Nested interface
interface Maintenance {
void performMaintenance();
}
}
Access Modifiers for Interfaces
They have only two access modifiers when declared outside any other class. Nested interfaces can have all access modifiers.
- public: Can be accessed from any other class or interface in any package.
- default: Can be accessed only within its own package.