Java- Dynamic Method Dispatch | Run-time polymorphism



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


interface A{ int a=5; void add(); void sub(); } interface B{ void add(); void sub(); } class C implements B,A { public void add(){ //a+=10; System.out.println("Hello from addC a="+a); } public void sub(){ System.out.println("Hello from Class C sub"); } } class D implements B,A { public void add(){ //a+=10; System.out.println("Hello from addD a="+a); } public void sub(){ System.out.println("Hello from class D sub"); } } class Test{ //static int i; public static void main(String ar[]){ // Calc objCalc=new Calc(); A interA; B interB; C objC=new C(); D objD=new D(); //objC.add(); //objC.sub(); //objC.pow(); interA =objC; interA.add(); interA.sub(); interA =objD; interA.add(); interA.sub(); } }

Reactions: