Pages

interface progrmmes

/** Program to assign the object of a class to the reference of an interface */
interface Xyz
{
 public void funX();
 public void funY();
}
class X implements Xyz
{
 public void funX()
 {
 System.out.println("Inside funx");
 }
 public void funY()
 {
 System.out.println("Inside funY");
 }
 void fun1()
 {
 System.out.println("Inside fun1");
 }
}// end of class
class InDemo2
{
 public static void main(String args[])
 {
 Xyz x1=new X();//X implements Xyz
 x1.funX();
 x1.funY();
 //x1.fun1(); ->Error
 }// end main
}// end class
->Generally, the programmers think that through the concept of interfaces Java supports Multiple Inheritance. The following program is an example for that implements this concept.
/** Program that demonstrates Multiple Inheritance in Java */
interface Xyz
{
 public void funX();
 public void funY();
}
interface Abc
{
  public void funA();
  public void funB();
}
interface Mno extends Xyz,Abc
{
  public void funM();
  public void funN();
}
class Sample implements Mno
{
 public void funX()
 {
   System.out.println(“Inside funX”);
 }
public void funY()
 {
   System.out.println(“Inside funY”);
 }
public void funA()
 {
   System.out.println(“Inside funA”);
 }
public void funB()
 {
   System.out.println(“Inside funB”);
 }
public void funM()
 {
   System.out.println(“Inside funM”);
 }
public void funN()
 {
   System.out.println(“Inside funN”);
 }
}// end of  class
class InDemo3
{
public static void main(String args[])
{
  Sample s = new Sample();
  s.funX();
  s.funY();
  s.funA();
  s.funB();
  s.funM();
  s.funN();
 }// end of main
}// end of class
->in the above example, because the interface Mno is extending two interfaces (Abc, Xyz), programmers call it Multiple Inheritance. But, the methods of Mno, Abc and Xyz are provided bodies by the class Sample. That is, Mno is not getting anything from Abc and Xyz instead bodies for the methods of all the interfaces is provided by Sample class.
->Now let us see a program where we can create object for an interface.
/* Program for Creating object for an Interface */
interface Xyz
{
 public void funX();
 public void funY();
}
class InDemo
{
 public static void main(String args[])
 {
 Xyz x1 = new Xyz() {
 public void funX()
 {
 System.out.println("Inside funX");
 }
 public void funY()
 {
 System.out.println("Inside funY");
 }
};
 x1.funX();
 x1.funY();
 } //end of main
} //end of class

-> In the above program, it seems that we are creating object for the interface Xyz using ‘new’ operator. But, it is some class that is providing bodies for methods of the interface Xyz and its name is unknown. Such classes which implements an interface and without having a name are called "Anonymous Inner classes". Most of the classes in Java API are defined as Anonymous Inner classes.