java - Interfaces and dynamic method dispatch -
java - Interfaces and dynamic method dispatch -
normal overriding (without utilize of interfaces)
class { int x = 0; void show() { system.out.println("in a. x : " + x); } } class b extends { void show() { system.out.println("in b. x : " + x); } } class c extends { void show() { system.out.println("in c. x : " + x); } } class test { public static void main(string args[]){ obj = new b(); obj.show(); obj = new c(); obj.show(); } }
this same doing interfaces:
interface { int x = 0; void show(); } class b implements { public void show() { system.out.println("in b. x : " + x); } } class c implements { public void show() { system.out.println("in c. x : " + x); } } class test { public static void main(string args[]){ obj = new b(); obj.show(); obj = new c(); obj.show(); } }
output in both cases same , implementation similar. question is, why have interfaces when can same thing using dynamic method dispatch?
there points consider :
interface give alternative class extends other class.as know, can not extend multiple class can implement multiple interface (to accomplish multiple inheritance) . by extending class can not forcefulness sub-class override method define in super-class.while in implementation of interface forcefulness implement method in sub-class. it depend on implementation need. want sub-class must implement method need utilize interface design, while not bother sub-class override super-class method or not can used extends design.i hope create clear difference both design.
java method-overriding
Comments
Post a Comment