Java Interfaces
intermediatePart of Core Java
Theory
An interface in Java is a reference type that defines a contract of abstract methods. Classes implement interfaces to fulfill that contract.
Defining and Implementing Interfaces
interface Flyable {
void fly();
}
interface NoiseMaker {
void makeSound();
}
class Bird implements Flyable, NoiseMaker {
public void fly() {
System.out.println("Bird is flying");
}
public void makeSound() {
System.out.println("Chirp chirp");
}
}A class can implement multiple interfaces — this is Java's way of achieving multiple inheritance.
Default Methods (Java 8+)
Interfaces can have default methods with a body. Implementing classes can override them or use the default:
interface Vehicle {
void start();
default void honk() {
System.out.println("Beep beep!");
}
}Functional Interfaces and Lambdas
A functional interface has exactly one abstract method. It can be implemented with a lambda expression:
@FunctionalInterface
interface Greeter {
String greet(String name);
}
Greeter g = name -> "Hello, " + name;
System.out.println(g.greet("Alice"));Comparator vs Comparable
- Comparable — defines natural ordering (
compareToin the class itself) - Comparator — defines custom ordering (separate class or lambda)
Comparable and Comparator Example
javaPractical Examples
Example: Functional Interface with Lambda
javaExercises
Shape Interface with Comparator
Define a Shape interface with a getArea() method. Create Circle and Rectangle classes that implement it. Then sort a list of shapes by area using Comparator.
Expected Output:
Circle(r=2): 12.57\nRectangle(3x4): 12.00\nCircle(r=5): 78.54