Jul 20, 2015

What happens when we create an object of interface?

Actually you cannot create an instance of an interface.
You create an instance of some class, implementing the interface. Actually there can be dozens of classes, implementing one interface. So when you use a variable of interface type, the only thing you are guaranteed is that the object, which is in fact referenced by the variable, implements the interface and you can use any of the interface methods, properties, etc.


interface IFoo
{
   void DoFoo();
}

class Foo1: IFoo
{
    public DoFoo()
    {
        //one implementation
    }
}

class Foo2: IFoo
{
    public DoFoo()
    {
        //the other implementation
    }
}

IFoo tmp = new Foo1();
tmp = new Foo2();
 
 
As far as i know You cannot create an instance of an interface and even 
if we do so it would be of no use as none of the members in that class 
are implemented. Same is the case with the abstract class. This is 
because they are incomplete (i.e., they act as templates) and creation 
of an object is not meaningful for incomplete classes 

No comments:

Post a Comment