Menu
Topics Index
...
`

NestedInterfaceDemo - Java Example Program


NestedInterfaceDemo
class Number implements Printnumbericvalue
{
    public static void main(String[] args)
    {
        Printnumbericvalue general = new Number(); // LINE A
        Printnumbericvalue.PrintInWords word = new Alphabet(); // LINE B
        general.print(1); // LINE C
        word.print("one"); // LINE D
    }
    
    public void print(int i)
    {
        System.out.println("Executed Print method in interface Printnumbervalue " + i);
    }
}

class Alphabet implements Printnumbericvalue.PrintInWords // LINE E
{

    public void print(String s)
    {
        System.out.println("Executed Print method in interface PrintInWords " + s);
    }
}

interface Printnumbericvalue
{

    public void print(int i);

    interface PrintInWords
    {

        public void print(String s);
    }
}
OUTPUT

Executed Print method in interface Printnumbervalue 1
Executed Print method in interface PrintInWords one

DESCRIPTION

In the above example we have declared an interface PrintInWords inside Printnumbervalue. At LINE A we have created an object for Number using Printnumbericvalue interface reference. At LINE B we have created an object for Alphabet using PrintInWords interface reference. At LINE C we are calling print method which is residing in Number class. At LINE D we are calling print method which is residing in Alphabet class.

THINGS TO TRY
  • At LINE B remove Printnumbericvalue which is before PrintInWords word. The program runs fine and the output will be same because we can create reference to the nested interface without referring to its outer interface.
  • In the same way at LINE E remove Printnumbericvalue which is before PrintInWords. Compilation error is thrown Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from Alphabet to Printnumbericvalue.PrintInWords. This is because we cannot access nested interface without referring to its outer interface.

© meritcampus 2019

All Rights Reserved.

Open In App