Tuesday 18 February 2014

Interface inside an Interface

Interface can be defined in other interface. By default the inner interface is static.

A nested interface is any interface whose declaration occurs within the body of another class or interface.

Syntax
    interface Interface1{

        interface Interface2{

        }

    }

Example1
interface Sum{
 int sum(int a, int b);

 interface SumThree{
  int sum(int a, int b, int c);
 }

 interface SumFour{
  int sum(int a, int b, int c);
 }
}

class SumTest implements Sum{
  
 public int sum(int a1, int b1){
  return (a1+b1);
 }

 public static void main(String args[]){
  SumTest s1 = new SumTest();
  System.out.println(s1.sum(10,20));
 }
 
}

Output
30

Example2
class SumTest1 implements Sum.SumThree{

 public int sum(int a1, int b1, int c1){
  return (a1+b1+c1);
 }

 public static void main(String args[]){
  SumTest1 s1 = new SumTest1();
  System.out.println(s1.sum(10,20,30));
 }
 
}

Output
60

Some Points to Remember
1. Declaring class inside blocks is valid in java. Example : Local classes
class SumTest{
 {
  class ABC{
  }
 }
}
    
2. You can't declare interface inside a block
class SumTest{ 
 {
  interface ABC{
  }
 }
}


When you tries to compile the above program, compiler throws the below error
SumTest.java:4: error: interface not allowed here
interface ABC{
^
1 error


Class inside interface                                                 Java8 Enhancement to interfaces                                                 Home

No comments:

Post a Comment