Java Interfaces
An interface in Java is a reference type, similar to a class, that can contain method signatures and constants. Interfaces provide a way to achieve abstraction and multiple inheritance (since a class can implement multiple interfaces). They define a contract that implementing classes must fulfill.
Key Topics
1. Defining Interfaces
Interfaces are defined using the interface
keyword. Methods in interfaces are abstract by default (prior to Java 8). From Java 8 onwards, interfaces can also contain default and static methods.
public interface Animal {
void makeSound(); // Abstract method
}
2. Implementing Interfaces
Classes implement interfaces using the implements
keyword and must provide implementations for all abstract methods.
public class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("Bark");
}
}
3. Default Methods
From Java 8 onwards, interfaces can have default methods with an implementation. This allows interfaces to evolve without breaking existing implementations.
public interface Vehicle {
void start(); // Abstract method
// Default method
default void stop() {
System.out.println("Vehicle stopped.");
}
}
4. Implementing Multiple Interfaces
A class can implement multiple interfaces, allowing it to inherit the abstract methods of all the interfaces.
public interface Flyable {
void fly();
}
public interface Swimmable {
void swim();
}
public class Duck implements Flyable, Swimmable {
@Override
public void fly() {
System.out.println("Duck is flying.");
}
@Override
public void swim() {
System.out.println("Duck is swimming.");
}
}
5. Key Takeaways
- Interfaces define a contract that implementing classes must fulfill.
- Use the
implements
keyword to implement an interface. - Interfaces support multiple inheritance in Java.
- Default methods allow interfaces to have method implementations.
- Interfaces promote loose coupling and enhance code flexibility.