
Java Interface
The Java interface is a fundamental concept in object-oriented programming that defines a contract or a set of abstract methods that a class must implement. Interfaces provide a way to achieve abstraction and multiple inheritance in Java. Here are the key characteristics and rules associated with Java interfaces:
- Declaring an Interface:
- You define an interface using the
interface
keyword in its declaration. - An interface can only contain constant (static final) fields and method signatures, but it cannot have fields with values or method implementations.
- Abstract Methods:
- Interfaces can include abstract method signatures. These methods are declared without providing an implementation (i.e., no method body).
- Any class that implements an interface must provide concrete (i.e., non-abstract) implementations for all methods defined in the interface.
- Default Methods (Java 8 and later):
- Starting from Java 8, interfaces can include default methods. Default methods are methods with a provided implementation in the interface itself.
- Classes that implement the interface are not required to provide their own implementation for default methods. However, they can override default methods if needed.
- Static Methods (Java 8 and later):
- Starting from Java 8, interfaces can also include static methods with implementations.
- These methods are called on the interface itself and do not require an instance of the implementing class.
- Multiple Inheritance:
- Java interfaces support multiple inheritance, allowing a class to implement multiple interfaces.
- This enables a class to inherit the abstract methods and constants from multiple interfaces, but it also requires the class to provide implementations for all methods.
- Implements Keyword:
- To indicate that a class implements an interface, you use the
implements
keyword followed by the interface name in the class declaration.
Here’s an example of an interface and a class that implements it:
interface Vehicle {
void start();
void stop();
}
class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car started.");
}
@Override
public void stop() {
System.out.println("Car stopped.");
}
}
In this example, the Vehicle
interface defines two abstract methods, start
and stop
. The Car
class implements the Vehicle
interface and provides concrete implementations for both methods. The @Override
annotation is used to indicate that the methods in the Car
class are overrides of the methods defined in the interface.
Interfaces are commonly used in Java to define contracts for classes, enabling multiple classes to adhere to the same contract while providing their own specific implementations. This promotes a high level of code reusability and flexibility in object-oriented programming.