Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cast to an interface?

In Jesse Liberty's Programming C# (p.142) he provides an example where he casts an object to an interface.

 interface IStorable  {     ...  }   public class Document : IStorable  {     ...  }   ...  IStorable isDoc = (IStorable) doc;    ... 

What is the point of this, particularly if the object's class implements the inteface anyway?

EDIT1: To clarify, I'm interested in the reason for the cast (if any), not the reason for implementing interfaces. Also, the book is his 2001 First Edition (based on C#1 so the example may not be germane for later versions of C#).

EDIT2: I added some context to the code

like image 243
eft Avatar asked Mar 06 '09 17:03

eft


People also ask

What is casting to an interface?

A type cast—or simply a cast— is an explicit indication to convert a value from one data type to another compatible data type. A Java interface contains publicly defined constants and the headers of public methods that a class can define.

Why would you want to use an interface?

Why do we use an Interface? It is used to achieve total abstraction. Since java does not support multiple inheritances in the case of class, by using an interface it can achieve multiple inheritances. It is also used to achieve loose coupling.

Should you always use an interface?

No, every class should not have an interface. It's overkill squared. You use an interface when you need to abstract what's done from how it's done, and you're certain that the implementation can change.

Can a class be casted to an interface?

Yes, you can. If you implement an interface and provide body to its methods from a class. You can hold object of the that class using the reference variable of the interface i.e. cast an object reference to an interface reference.


2 Answers

Because you want to restrict yourself to only methods provided by the interface. If you use the class, you run the risk of calling a method (inadvertently) that's not part of the interface.

like image 183
Tundey Avatar answered Oct 11 '22 05:10

Tundey


There is only one reason when you actually need a cast: When doc is of a base type of an actual object that implements IStorable. Let me explain:

public class DocBase {   public virtual void DoSomething()   {    } }  public class Document : DocBase, IStorable {   public override void DoSomething()   {     // Some implementation     base.DoSomething();   }    #region IStorable Members    public void Store()   {     // Implement this one aswell..     throw new NotImplementedException();   }    #endregion }  public class Program {   static void Main()   {     DocBase doc = new Document();     // Now you will need a cast to reach IStorable members     IStorable storable = (IStorable)doc;   } }  public interface IStorable {   void Store(); } 
like image 30
Jeroen Landheer Avatar answered Oct 11 '22 07:10

Jeroen Landheer