Tuesday, 18 February 2014

Class inside an Interface

A class can be defined in an interface, By default the class defined in interface is public and static. Just like accessing the static final variables in the interface, we can access the class defined in the interface.

Example
interface InterfaceEx{
 double PI=3.142;
 
 class Employee{
  String firstName;
  String lastName;
 }

 String getEmployee();
 void setEmployee(Employee e);
}

class InterfaceExTest implements InterfaceEx{
 Employee emp;
 
 public String getEmployee(){
  return emp.firstName +"\t" + emp.lastName;
 }

 public void setEmployee(Employee emp){
  this.emp = emp;
 }

 public static void main(String args[]){
  Employee e1 = new Employee();
  e1.firstName = "abc";
  e1.lastName = "def";
  
  InterfaceExTest obj1 = new InterfaceExTest();
  obj1.setEmployee(e1);
  System.out.println(obj1.getEmployee());
 }
}
  
Output
abc def

Some points to Remember
1. A class defined in interface can implement the same interface.
interface InterfaceEx{

 class ClassInside implements InterfaceEx{
  public void print1(){
   System.out.println(" I am print1");
  }
 }
 
 void print1();
}

class InterfaceExTest{
 public static void main(String args[]){
  InterfaceEx.ClassInside e1 = new InterfaceEx.ClassInside();
  e1.print1();
 }
}

Output
I am print1

2. The class defined in an interface is public and static by default.

3. Can an abstract class defined in interface ?
Yes      
interface InterfaceEx{

 abstract class ClassInside implements InterfaceEx{
  public void print1(){
   System.out.println(" I am print1");
  }
 }
 
 void print1();
 void print2();
}

class InterfaceExTest{

 public static void main(String args[]){
  InterfaceEx.ClassInside e1 = new InterfaceEx.ClassInside(){
   public void print2(){
    System.out.println("I am in print2");
   }
  };
  
  e1.print1();
  e1.print2();
 }
}

Output
I am print1
I am in print2

4. Can I override the methods defined in the class, by the same class object ?
Yes, It is possible by using Anonymous classes.
Example
interface InterfaceEx{
 class ClassInside implements InterfaceEx{
  public void print1(){
   System.out.println(" I am print1");
  } 
  public void print2(){
   System.out.println(" I am print2");
  }
 }
 
 void print1();
 void print2();
}

class InterfaceExTest{
 public static void main(String args[]){
  InterfaceEx.ClassInside e1;
  e1 = new InterfaceEx.ClassInside(){
     public void print2(){
      System.out.println("Overriding print2");
     }
     
     public void print1(){
      System.out.println("Overriding print1");
     }
    };
    
  e1.print1();
  e1.print2();
 }
}
 
Output
Overriding print1
Overriding print2

As you see, the methods defined by the class “ClassInside” are overridden using Anonymous class.
.

Extend interface                                                 Interface in interface                                                 Home

No comments:

Post a Comment