Accessing Interface Methods
You
can
access the members of the IStorable
interface as
if they were members of the Document
class:
Document doc = new Document("Test Document"); doc.status = -1; doc.Read( );
or you can create an instance of the interface by casting the document to the interface type, and then use that interface to access the methods:
IStorable isDoc = (IStorable) doc; isDoc.status = 0; isDoc.Read( );
In this case, in Main( )
you know that
Document
is in fact an
IStorable
, so you can take advantage of that
knowledge.
Tip
As stated earlier, you cannot instantiate an interface directly. That is, you cannot say:
IStorable isDoc = new IStorable( );
You can, however, create an instance of the implementing class, as in the following:
Document doc = new Document("Test Document");
You can then create an instance of the interface by casting the
implementing object to the interface type
,
which in this case is IStorable
:
IStorable isDoc = (IStorable) doc;
You can combine these steps by writing:
IStorable isDoc = (IStorable) new Document("Test Document");
In general, it is a better design decision to access the interface
methods through an interface reference. Thus, it is better to use
isDoc.Read( )
, than doc.Read( )
, in the previous example. Access through an interface allows you to treat the interface polymorphically. In other words, you can have two or more classes implement the interface, and then by accessing these classes only through the interface, you can ignore their real runtime ...
Get Programming C# now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.