Angloos
Angloos

Reputation: 780

Accessing objects through their interfaces

What does it really mean? I am reading design pattern book. It says objects are accessed solely through their interfaces, and I am not able to get my head around it, can some body give me an example (Will really appreciate if its in C#)

What do we really achieve by using it?

Thanks

Upvotes: 4

Views: 4895

Answers (5)

Vikram
Vikram

Reputation: 1627

That really depends. If the variable is of type "interface", then in that case the object can be accessed by the interface type only.

Let's consider an example - Suppose I have an interface as defined below -

interface IMyInterface
{
   string B();
}

and if I implement this interface using a class "MyClass" as shown below -

public class MyClass:IMyInterface
   {
      public string B()
      { 
           return "In Class";
      }
   }

   public class MyAnotherClass:IMyInterface
       {
          public string B()
          { 
               return "In Another Class";
          }
       }

and I create an instance of the class using the interface as shown below

   IMyInterface myinst = new MyClass();

then in the above case I can only get access to the Method B() using variable myinst which contains a reference to MyClass type.

Going further, let's say I have a method that takes a parameter of type IMyInterface as shown below -

    public class UseOfInterface{
    public void InterfaceUse(IMyInterface myPara)
    {
      myPara.B();
    }
}

and I call this method as 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 Another Class"

Then, as shown above, it is decided at runtime as to which method is called using the Interface variable.

But if I had created a variable of type MyClass which would have contained a reference of type MyClass itself as shown below -

   MyClass myinst = new MyClass();

then method B() can be accessed using the MyClass instance. So it depends what type of scenario you are dealing with.

Edit: Why Use Interfaces?

The main reason to use an interface is that it provides a contract to the class for which it is being implemented apart from the multiple inheritance support in C#. Let's can see an example where the contract providing can be helpful.

Suppose you have a class - "Car" in your assembly that you want to expose publicly, the definition of the class is as shown below

namespace CarNameSpace
{
   public class Car()
   {
      public void Drive(IDriver driver)
      {
         if(driver.Age > 18)
         {
            driver.Drive();
         }
      }
   }
}

As shown above, anyone who implements the IDriver interface can drive the car, which is defined below,

interface IDriver
{
   string Age{get; set;}
   string Name {get set;}
   string Drive()
}

In turn to drive my car I would be exposing the IDriver interface to the outer world, so anyone who implements my interface can call the Car's Drive method, doesn't matter how he drives the car as 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 be used as shown below

  PerfectDriver perf = new PerfectDriver
  Car myCar = Car();  
  myCar.Driver(perf);

Upvotes: 1

Craig
Craig

Reputation: 119

The interface refers to what the object exposes to users of the object. An object will be an instance of a class which will have its own interface and possibly implement one or more other interfaces.

While languages such as C# allow you to define things called interfaces, those are distinct from the interface referred to in the statement that objects are accessed through their interfaces. In a language such as Scala, for instance, what C# calls an interface is called a trait. Most design patterns do involve the use of defined interfaces, i.e. public interface <interface name>, but again, those are distinct from what is meant in the original statement.

Suppose I define the following class in C#:

public class MyType
{
  public void Method1()
  {
    ...
  }

  private void Method2()
  {
    ...
  }

  public int Method3()
  {
    ...
  }
}

Then the interface through which I interact with the class is the two methods it exposes, void Method1 and int Method2 and the implicit parameterless constructor.

Now, suppose I define the following interfaces and class:

public interface IInterface1
{
    void Method1();
}

public interface IInterface2
{
    int Method3();
}

public class MyType2 : IInterface1, IInterface2
{
  public void Method1()
  {
    ...
  }

  private void ADifferentMethod()
  {
    ...
  }

  public int Method3()
  {
    ...
  }
}

The interface through which a user interacts with instances of MyType2 is the same as that through which a user interacts with instances of MyType1 (except for the different constructors) because the signatures of the public methods (and other public members) are identical : void Method1 and int Method3.

Upvotes: 0

Mark Shevchenko
Mark Shevchenko

Reputation: 8197

The problem is the interface has several meanings. In this case the author is talking that objects must be accessed through public methods (in C# through public properties also) only.

(Of course, inheritors may use protected methods).

Public methods/properties form the public interface of a class. It's not the same interface that described by interface keyword in C#.

Upvotes: 2

Mik3c
Mik3c

Reputation: 11

An interface is a construct that describes the signature of the public members of an object. It contains declarations (declarations only, no implementation) of properties, methods and events that are guaranteed to be present on any object that implements that interface.

Here's a simple interface and a few classes that implement it. The interface "INamed" states simply that objects implementing the interface have a "Name" property that is a string.

public interface INamed{
    string Name{get;}
}

public class Person : INamed{
    public string Name{get;set;}
}

public class Place : INamed{
    public string Name{get;set;}
}

public class Thing : INamed{
    public string Name{get;set;}
}

...And a simple method that accepts a parameter of that interface type.

static void PrintName(INamed namedObject){
    Console.WriteLine(namedObject.Name);
}

This "PrintName" method can accept a parameter of any type that implements that interface. The advantage of "accessing objects by their interface" is that it infuses your application with a certain flexibility, accessing these interfaces as opposed to their concrete types allows you to operate on these objects without having to know what they really are.

I could, for instance choose to operate on the IDbCommand interface as opposed to a concrete SqlCommand and much of what I write in this manner will be useful when working with a variety of database providers.

The simple idea is that you don't need to know if you're in a car or a boat because you can drive anything with a wheel and pedals.

Upvotes: 0

RobCroll
RobCroll

Reputation: 2589

If you have a class called Espson and it implements an interface called IPrinter then you can instantiate the object by it's interface.

IPrinter printer = new Espson();

Epson may have a number of methods that are not part of the IPrinter interface but you may not care. All you may want to do is call a method defined in the IPrinter interface called Print

So then I can pass the class to a method called PrintDocument(IPrinter printer) and the method doesn't care what type of printer it is, it just knows it has a method called Print

Upvotes: 2

Related Questions