Java Interface Examples


// Example of Interface achieving dynamic method dispatch
//or (Run time polymorphism)

interface A
{
public void add();
}

class  B implements A
{
public void add()
{

System.out.println("Hello from B add()");
}
}

class  C implements A
{
public void add()
{

System.out.println("Hello from C add()");
}
}

class Test
{
public static void main(String ar[])
{
A objA; //Defining object of interface A

B objB =new B();
C objC =new C();

objA=objB; //Assigning referance of object of B to objA

objA.add();// now JVM  at run time resolves which method to call


objA=objC;//Assigning referance of object of C to objA


objA.add();

}
}

Reactions: