You can access the members of an interface through an object of any class that implements the interface. For example, because Document
implements IStorable
, you can access the IStorable
methods and property through any Document
instance:
Document doc = new Document("Test Document"); doc.Status = -1; doc.Read( );
At times, though, you won’t know that you have a Document
object; you’ll only know that you have objects that implement IStorable
, for example, if you have an array of IStorable
objects, as we mentioned earlier. You can create a reference of type IStorable
, and assign that to each member in the array, accessing the IStorable
methods and property. You cannot, however, access the Document
-specific methods because all the compiler knows is that you have an IStorable
, not a Document
.
As we mentioned before, you cannot instantiate an interface directly; that is, you cannot write:
IStorable isDoc = new IStorable;
You can, however, create an instance of the implementing class and then assign that object to a reference to any of the interfaces it implements:
Document myDoc = new Document(…); IStorable myStorable = myDoc;
You can read this line as “assign the IStorable
-implementing object myDoc
to the IStorable
reference myStorable
.”
You are now free to use the IStorable
reference to access the IStorable
methods and properties of the document:
myStorable.Status = 0; myStorable.Read( );
Notice that the IStorable
reference myStorable
has access to the IStorable
automatic property Status
. However, myStorable
would not have access to the Document
’s private member variables, if it had any. The IStorable
reference knows only about the IStorable
interface, not about the Document
’s internal members.
Thus far, you have assigned the Document
object (myDoc
) to an IStorable
reference.