About Lesson
In Java, you can define interfaces within other interfaces or within classes. These are called nested interfaces. Nested interfaces are useful for organizing code, creating contracts specific to certain classes or interfaces, and improving code readability. Let’s explore nested interfaces with detailed notes and examples.
Nested Interface Syntax
Here’s the general syntax for declaring a nested interface within an outer interface:
public interface OuterInterface {
// Outer interface members
// Nested interface declaration
interface NestedInterface {
// Nested interface members
}
}
And within a class:
public class OuterClass {
// Outer class members
// Nested interface declaration
interface NestedInterface {
// Nested interface members
}
}
Example: Nested Interface within an Interface
public interface Vehicle {
void start();
void stop();
// Nested interface
interface Engine {
void run();
}
}
Implementing Nested Interface
public class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car started.");
}
@Override
public void stop() {
System.out.println("Car stopped.");
}
// Implementing the nested interface method
class CarEngine implements Vehicle.Engine {
@Override
public void run() {
System.out.println("Car engine running.");
}
}
}
Example: Nested Interface within a Class
public class OuterClass {
// Outer class members
// Nested interface
interface InnerInterface {
void display();
}
// Inner class implementing the nested interface
class InnerClass implements InnerInterface {
@Override
public void display() {
System.out.println("Inner class implementing nested interface.");
}
}
}
Using Nested Interfaces
public class Main {
public static void main(String[] args) {
// Using nested interface within an interface
Vehicle car = new Car();
car.start();
car.stop();
Vehicle.Engine engine = new Car().new CarEngine();
engine.run(); // Output: Car engine running.
// Using nested interface within a class
OuterClass.InnerInterface inner = new OuterClass().new InnerClass();
inner.display(); // Output: Inner class implementing nested interface.
}
}