The following code shows an Example of Nested Interface in Java.

In Java, you can nest interfaces within other interfaces or classes. This allows you to create more structured and modular code. For instance, given below an example demonstrating how to nest interfaces in Java.

public class NestedInterfaceDemo {
    // Outer interface
    interface Shape {
        void draw();

        // Nested interface
        interface Colorable {
            void setColor(String color);
        }
    }

    // Implementing the nested interface
    static class Circle implements Shape, Shape.Colorable {
        private String color;

        @Override
        public void draw() {
            System.out.println("Drawing a circle");
        }

        @Override
        public void setColor(String color) {
            this.color = color;
        }

        public void printColor() {
            System.out.println("Circle color: " + color);
        }
    }

    public static void main(String[] args) {
        Circle circle = new Circle();
        circle.draw();
        circle.setColor("Red");
        circle.printColor();
    }
}

In this example:

  1. We have an outer interface called Shape, which declares a method draw(). Inside the Shape interface, there’s a nested interface called Colorable, which declares a method setColor(String color).
  2. Then, we have a class called Circle that implements both the Shape and Shape.Colorable interfaces. It provides concrete implementations for the draw() method from the outer interface and the setColor(String color) method from the nested interface.
  3. In the main method, we create an instance of the Circle class, call its methods to draw the circle, set its color, and print the color.

This demonstrates the nesting of interfaces in Java, where the nested interface Colorable is accessible within the outer interface Shape, and the class Circle implements both the outer and nested interfaces.



Further Reading

Spring Framework Practice Problems and Their Solutions

From Google to the World: The Story of Go Programming Language

Why Go? Understanding the Advantages of this Emerging Language

Creating and Executing Simple Programs in Go

20+ Interview Questions on Go Programming Language

Java Practice Exercise

programmingempire

Princites