Understanding Interfaces
What is an Interface?
An interface in Java is a blueprint or a contract that defines a set of methods, constants, and default methods. Interfaces are used to achieve abstraction and provide a way to define common behavior across unrelated classes.
Characteristics of Interfaces
- Cannot be Instantiated: Interfaces cannot be instantiated directly. They are used as a template for classes to implement.
- All Methods are Abstract by Default: All methods in an interface are abstract by default, meaning they have no implementation. The implementing classes must provide the implementation for these methods.
- All Fields are Public, Static, and Final by Default: All fields (variables) in an interface are automatically public, static, and final.
- Can Contain Default and Static Methods: Interfaces can now have default and static methods, which provide a way to add new functionality without breaking existing implementations.
- Multiple Inheritance: A class can implement multiple interfaces, allowing for a form of multiple inheritance.
When to Use Interfaces?
Interfaces are useful when you want to define a common set of methods or behaviors that multiple unrelated classes should implement. This promotes code reuse, flexibility, and maintainability. Interfaces are often used to define a contract or a standard that classes must adhere to, without specifying the implementation details.
Example of an Interface
// Interface
public interface Flyable {
public static final double MAX_SPEED = 500.0; // public, static, final by default
public abstract void fly(); // public and abstract by default
default void land() {
System.out.println("The object is landing.");
}
static void takeOff() {
System.out.println("The object is taking off.");
}
}
// Class implementing the interface
public class Airplane implements Flyable {
@Override
public void fly() {
System.out.println("The airplane is flying.");
}
}
// Another class implementing the interface
public class Bird implements Flyable {
@Override
public void fly() {
System.out.println("The bird is flying.");
}
}