Tuesday, 15 July 2014

Interface as a Type in java -



Interface as a Type in java -

this question has reply here:

when should 1 utilize interfaces? 17 answers

i see people creating instance of class , assigning reference variable of type interface class implements.

interface { void display(); } public class interfaceobject implements { public void display(){ system.out.println("show this.."); } public static void main(string[] args) { aobj = new interfaceobject(); aobj.display();//outout:show this.. interfaceobject bobj = new interfaceobject(); bobj.display();//outout:show this.. } }

here object aobj interface object , object bobj direct instance of class implementing interface. phone call display() through both objects yeild same result. question: advantage of creating interface object(reference variable of interface type)? add together more confusion code? ofcourse, not case.

the classic illustration of interface (or abstract type) of shape. let's writing programme displays shapes -- triangles, rectangles, circles, etc. of them can implement methods allow them displayed on screen -- say, display(screen) method -- each shape knows how itself.

but implementing 'shape' interface, , treating objects shapes, code handling shapes not have know handling each type of shape, methods mutual shape. that's advantage. display portion of programme can have collection of these , deal them without having know individual characteristics.

this kind of generality applicable many situations.

java interface

No comments:

Post a Comment