what mean? reading design pattern book. says objects accessed solely through interfaces, , not able head around it, can body give me example (will appreciate if in c#)
what achieve using it?
thanks
that depends if variable if of type interface, in case object can accessed interface type only.
let take case suppose have interface defined below
interface imyinterface { string b(); }
and if derive class interface shown below
public class myclass:imyinterface { public string b() { return "in class"; } } public class myanotherclass:imyinterface { public string b() { return "in class"; } }
and create instance of class using interface shown below
imyinterface myinst = new myclass();
here in above case can access method b() using variable myinst contains reference myclass type.
going further if have method takes parameter of type imyinterface shown below
public class useofinterface{ public void interfaceuse(imyinterface mypara) { mypara.b(); } }
and call method shown below -
imyinterface myinst = new myclass(); imyinterface myanotherinst = new myanotherclass(); useofinterface interfaceuse = new useofinterface(); interfaceuse.interfaceuse(myinst); // returns "in class" interfaceuse.interfaceuse(myanotherinst); // returns "in class"
as shown in above case is decided @ run time method call using interface variable.
but if have created variable of type myclass have contained reference of type myclass shown below
myclass myinst = new myclass();
in case method b() can accessed using myclass instance. depends type of scenario dealing with.
edit: why use interface
the main reason use interface provides contract class being implemented apart multiple inheritance support in c#. can see example contract thing can helpful.
suppose have car class in assembly want expose outer world, definition of class shown below
namespace carnamespace { public class car() { public void drive(idriver driver) { if(dirver.age > 18) { driver.drive(); } } } }
as shown above example can drive car implements idriver interface defined below,
interface idriver { string age{get; set;} string name {get set;} string drive() }
in turn drive car exposing idriver interface outer world, implements interface can call car's drive method, doesn't matter how dirves car shown below
public class perfectdriver:idriver { public perfectdriver() { name = "vikram"; age = 30; } public int age{get; set;} public string name {get; set;} public string drive() { return "drive's perfectly"; } }
the car class can used shown below
perfectdriver perf = new perfectdriver car mycar = car(); mycar.driver(perf);
Comments
Post a Comment