Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I seem to grasp interfaces?

Tags:

oop

interface

People also ask

Why are interfaces important?

A good User Interface is important because it can turn potential visitors to buyers as it facilitates interaction between the user and your website or application. It does not only focus only on the aesthetics but also maximizes responsiveness, efficiency and accessibility of a website.

Can an abstract class implement an interface?

Java Abstract class can implement interfaces without even providing the implementation of interface methods. Java Abstract class is used to provide common method implementation to all the subclasses or to provide default implementation.

Why should we not extend an interface?

A class can't extend an interface because inheriting from a class ( extends ), and implementing an interface ( implements ) are two different concepts. Hence, they use different keywords.

When to use abstract class vs interface?

Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes. If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.


Interfaces allow you to program against a "description" instead of a type, which allows you to more-loosely associate elements of your software.

Think of it this way: You want to share data with someone in the cube next to you, so you pull out your flash stick and copy/paste. You walk next door and the guy says "is that USB?" and you say yes - all set. It doesn't matter the size of the flash stick, nor the maker - all that matters is that it's USB.

In the same way, interfaces allow you to generisize your development. Using another analogy - imagine you wanted to create an application that virtually painted cars. You might have a signature like this:

public void Paint(Car car, System.Drawing.Color color)...

This would work until your client said "now I want to paint trucks" so you could do this:

public void Paint (Vehicle vehicle, System.Drawing.Color color)...

this would broaden your app... until your client said "now I want to paint houses!" What you could have done from the very beginning is created an interface:

public interface IPaintable{
   void Paint(System.Drawing.Color color);
}

...and passed that to your routine:

public void Paint(IPaintable item, System.Drawing.Color color){
   item.Paint(color);
}

Hopefully this makes sense - it's a pretty simplistic explanation but hopefully gets to the heart of it.


Interfaces establish a contract between a class and the code that calls it. They also allow you to have similar classes that implement the same interface but do different actions or events and not have to know which you are actually working with. This might make more sense as an example so let me try one here.

Say you have a couple classes called Dog, Cat, and Mouse. Each of these classes is a Pet and in theory you could inherit them all from another class called Pet but here's the problem. Pets in and of themselves don't do anything. You can't go to the store and buy a pet. You can go and buy a dog or a cat but a pet is an abstract concept and not concrete.

So You know pets can do certain things. They can sleep, or eat, etc. So you define an interface called IPet and it looks something like this (C# syntax)

public interface IPet
{
    void Eat(object food);
    void Sleep(int duration);
}

Each of your Dog, Cat, and Mouse classes implement IPet.

public class Dog : IPet

So now each of those classes has to have it's own implementation of Eat and Sleep. Yay you have a contract... Now what's the point.

Next let's say you want to make a new object called PetStore. And this isn't a very good PetStore so they basically just sell you a random pet (yes i know this is a contrived example).

public class PetStore
{
     public static IPet GetRandomPet()
     {    
          //Code to return a random Dog, Cat, or Mouse
     } 
}

IPet myNewRandomPet = PetStore.GetRandomPet();
myNewRandomPet.Sleep(10);

The problem is you don't know what type of pet it will be. Thanks to the interface though you know whatever it is it will Eat and Sleep.

So this answer may not have been helpful at all but the general idea is that interfaces let you do neat stuff like Dependency Injection and Inversion of Control where you can get an object, have a well defined list of stuff that object can do without ever REALLY knowing what the concrete type of that object is.


The easiest answer is that interfaces define a what your class can do. It's a "contract" that says that your class will be able to do that action.

Public Interface IRollOver
    Sub RollOver()
End Interface

Public Class Dog Implements IRollOver
    Public Sub RollOver() Implements IRollOver.RollOver
        Console.WriteLine("Rolling Over!")
    End Sub
End Class

Public Sub Main()
    Dim d as New Dog()
    Dim ro as IRollOver = TryCast(d, IRollOver)
    If ro isNot Nothing Then
        ro.RollOver()
    End If
End Sub

Basically, you are guaranteeing that the Dog class always has the ability to roll over as long as it continues to implement that Interface. Should cats ever gain the ability to RollOver(), they too could implement that interface, and you can treat both Dogs and Cats homogeneously when asking them to RollOver().


When you drive a friend's car, you more or less know how to do that. This is because conventional cars all have a very similar interface: steering wheel, pedals, and so forth. Think of this interface as a contract between car manufacturers and drivers. As a driver (the user/client of the interface in software terms), you don't need to learn the particulars of different cars to be able to drive them: e.g., all you need to know is that turning the steering wheel makes the car turn. As a car manufacturer (the provider of an implementation of the interface in software terms) you have a clear idea what your new car should have and how it should behave so that drivers can use them without much extra training. This contract is what people in software design refer to as decoupling (the user from the provider) -- the client code is in terms of using an interface rather than a particular implementation thereof and hence doesn't need to know the details of the objects implementing the interface.


Interfaces are a mechanism to reduce coupling between different, possibly disparate parts of a system.

From a .NET perspective

  • The interface definition is a list of operations and/or properties.
  • Interface methods are always public.
  • The interface itself doesn't have to be public.

When you create a class that implements the interface, you must provide either an explicit or implicit implementation of all methods and properties defined by the interface.

Further, .NET has only single inheritance, and interfaces are a necessity for an object to expose methods to other objects that aren't aware of, or lie outside of its class hierarchy. This is also known as exposing behaviors.

An example that's a little more concrete:

Consider is we have many DTO's (data transfer objects) that have properties for who updated last, and when that was. The problem is that not all the DTO's have this property because it's not always relevant.

At the same time we desire a generic mechanism to guarantee these properties are set if available when submitted to the workflow, but the workflow object should be loosely coupled from the submitted objects. i.e. the submit workflow method shouldn't really know about all the subtleties of each object, and all objects in the workflow aren't necessarily DTO objects.

// First pass - not maintainable
void SubmitToWorkflow(object o, User u)
{
  if (o is StreetMap)
  {
     var map = (StreetMap)o;
     map.LastUpdated = DateTime.UtcNow;
     map.UpdatedByUser = u.UserID;
  }
  else if (o is Person)
  {
     var person = (Person)o;
     person.LastUpdated = DateTime.Now; // Whoops .. should be UtcNow
     person.UpdatedByUser = u.UserID;
  }
  // Whoa - very unmaintainable.

In the code above, SubmitToWorkflow() must know about each and every object. Additionally, the code is a mess with one massive if/else/switch, violates the don't repeat yourself (DRY) principle, and requires developers to remember copy/paste changes every time a new object is added to the system.

// Second pass - brittle
void SubmitToWorkflow(object o, User u)
{
  if (o is DTOBase)
  {
     DTOBase dto = (DTOBase)o;
     dto.LastUpdated = DateTime.UtcNow;
     dto.UpdatedByUser = u.UserID;
  }

It is slightly better, but it is still brittle. If we want to submit other types of objects, we need still need more case statements. etc.

// Third pass pass - also brittle
void SubmitToWorkflow(DTOBase dto, User u)
{
  dto.LastUpdated = DateTime.UtcNow;
  dto.UpdatedByUser = u.UserID;

It is still brittle, and both methods impose the constraint that all the DTOs have to implement this property which we indicated wasn't universally applicable. Some developers might be tempted to write do-nothing methods, but that smells bad. We don't want classes pretending they support update tracking but don't.

Interfaces, how can they help?

If we define a very simple interface:

public interface IUpdateTracked
{
  DateTime LastUpdated { get; set; }
  int UpdatedByUser { get; set; }
}

Any class that needs this automatic update tracking can implement the interface.

public class SomeDTO : IUpdateTracked
{
  // IUpdateTracked implementation as well as other methods for SomeDTO
}

The workflow method can be made to be a lot more generic, smaller, and more maintainable, and it will continue to work no matter how many classes implement the interface (DTOs or otherwise) because it only deals with the interface.

void SubmitToWorkflow(object o, User u)
{
  IUpdateTracked updateTracked = o as IUpdateTracked;
  if (updateTracked != null)
  {
     updateTracked.LastUpdated = DateTime.UtcNow;
     updateTracked.UpdatedByUser = u.UserID;
  }
  // ...
  • We can note the variation void SubmitToWorkflow(IUpdateTracked updateTracked, User u) would guarantee type safety, however it doesn't seem as relevant in these circumstances.

In some production code we use, we have code generation to create these DTO classes from the database definition. The only thing the developer does is have to create the field name correctly and decorate the class with the interface. As long as the properties are called LastUpdated and UpdatedByUser, it just works.

Maybe you're asking What happens if my database is legacy and that's not possible? You just have to do a little more typing; another great feature of interfaces is they can allow you to create a bridge between the classes.

In the code below we have a fictitious LegacyDTO, a pre-existing object having similarly-named fields. It's implementing the IUpdateTracked interface to bridge the existing, but differently named properties.

// Using an interface to bridge properties
public class LegacyDTO : IUpdateTracked
{
    public int LegacyUserID { get; set; }
    public DateTime LastSaved { get; set; }

    public int UpdatedByUser
    {
        get { return LegacyUserID; }
        set { LegacyUserID = value; }
    }
    public DateTime LastUpdated
    {
        get { return LastSaved; }
        set { LastSaved = value; }
    }
}

You might thing Cool, but isn't it confusing having multiple properties? or What happens if there are already those properties, but they mean something else? .NET gives you the ability to explicitly implement the interface.

What this means is that the IUpdateTracked properties will only be visible when we're using a reference to IUpdateTracked. Note how there is no public modifier on the declaration, and the declaration includes the interface name.

// Explicit implementation of an interface
public class YetAnotherObject : IUpdatable
{
    int IUpdatable.UpdatedByUser
    { ... }
    DateTime IUpdatable.LastUpdated
    { ... }

Having so much flexibility to define how the class implements the interface gives the developer a lot of freedom to decouple the object from methods that consume it. Interfaces are a great way to break coupling.

There is a lot more to interfaces than just this. This is just a simplified real-life example that utilizes one aspect of interface based programming.

As I mentioned earlier, and by other responders, you can create methods that take and/or return interface references rather than a specific class reference. If I needed to find duplicates in a list, I could write a method that takes and returns an IList (an interface defining operations that work on lists) and I'm not constrained to a concrete collection class.

// Decouples the caller and the code as both
// operate only on IList, and are free to swap
// out the concrete collection.
public IList<T> FindDuplicates( IList<T> list )
{
    var duplicates = new List<T>()
    // TODO - write some code to detect duplicate items
    return duplicates;
}

Versioning caveat

If it's a public interface, you're declaring I guarantee interface x looks like this! And once you have shipped code and published the interface, you should never change it. As soon as consumer code starts to rely on that interface, you don't want to break their code in the field.

See this Haacked post for a good discussion.

Interfaces versus abstract (base) classes

Abstract classes can provide implementation whereas Interfaces cannot. Abstract classes are in some ways more flexible in the versioning aspect if you follow some guidelines like the NVPI (Non-Virtual Public Interface) pattern.

It's worth reiterating that in .NET, a class can only inherit from a single class, but a class can implement as many interfaces as it likes.

Dependency Injection

The quick summary of interfaces and dependency injection (DI) is that the use of interfaces enables developers to write code that is programmed against an interface to provide services. In practice you can end up with a lot of small interfaces and small classes, and one idea is that small classes that do one thing and only one thing are much easier to code and maintain.

class AnnualRaiseAdjuster
   : ISalaryAdjuster
{
   AnnualRaiseAdjuster(IPayGradeDetermination payGradeDetermination) { ...  }

   void AdjustSalary(Staff s)
   {
      var payGrade = payGradeDetermination.Determine(s);
      s.Salary = s.Salary * 1.01 + payGrade.Bonus;
   }
}

In brief, the benefit shown in the above snippet is that the pay grade determination is just injected into the annual raise adjuster. How pay grade is determined doesn't actually matter to this class. When testing, the developer can mock pay grade determination results to ensure the salary adjuster functions as desired. The tests are also fast because the test is only testing the class, and not everything else.

This isn't a DI primer though as there are whole books devoted to the subject; the above example is very simplified.


This is a rather "long" subject, but let me try to put it simple.

An interface is -as "they name it"- a Contract. But forget about that word.

The best way to understand them is through some sort of pseudo-code example. That's how I understood them long time ago.

Suppose you have an app that processes Messages. A Message contains some stuff, like a subject, a text, etc.

So you write your MessageController to read a database, and extract messages. It's very nice until you suddenly hear that Faxes will be also implemented soon. So you will now have to read "Faxes" and process them as messages!

This could easily turn into a Spagetti code. So what you do instead of having a MessageController than controls "Messages" only, you make it able to work with an interface called IMessage (the I is just common usage, but not required).

Your IMessage interface, contains some basic data you need to make sure that you're able to process the Message as such.

So when you create your EMail, Fax, PhoneCall classes, you make them Implement the Interface called IMessage.

So in your MessageController, you can have a method called like this:

private void ProcessMessage(IMessage oneMessage)
{
    DoSomething();
}

If you had not used Interfaces, you'd have to have:

private void ProcessEmail(Email someEmail);
private void ProcessFax(Fax someFax);
etc.

So, by using a common interface, you just made sure that the ProcessMessage method will be able to work with it, no matter if it was a Fax, an Email a PhoneCall, etc.

Why or how?

Because the interface is a contract that specifies some things you must adhere (or implement) in order to be able to use it. Think of it as a badge. If your object "Fax" doesn't have the IMessage interface, then your ProcessMessage method wouldn't be able to work with that, it will give you an invalid type, because you're passing a Fax to a method that expects an IMessage object.

Do you see the point?

Think of the interface as a "subset" of methods and properties that you will have available, despite the real object type. If the original object (Fax, Email, PhoneCall, etc) implements that interface, you can safety pass it across methods that need that Interface.

There's more magic hidden in there, you can CAST the interfaces back to their original objects:

Fax myFax = (Fax)SomeIMessageThatIReceive;

The ArrayList() in .NET 1.1 had a nice interface called IList. If you had an IList (very "generic") you could transform it into an ArrayList:

ArrayList ar = (ArrayList)SomeIList;

And there are thousands of samples out there in the wild.

Interfaces like ISortable, IComparable, etc., define the methods and properties you must implement in your class in order to achieve that functionality.

To expand our sample, you could have a List<> of Emails, Fax, PhoneCall, all in the same List, if the Type is IMessage, but you couldn't have them all together if the objects were simply Email, Fax, etc.

If you wanted to sort (or enumerate for example) your objects, you'd need them to implement the corresponding interface. In the .NET sample, if you have a list of "Fax" objects and want to be able to sort them by using MyList.Sort(), you need to make your fax class like this:

public class Fax : ISorteable 
{
   //implement the ISorteable stuff here.
}

I hope this gives you a hint. Other users will possibly post other good examples. Good luck! and Embrace the power of INterfaces.

warning: Not everything is good about interfaces, there are some issues with them, OOP purists will start a war on this. I shall remain aside. One drawback of an Interfce (in .NET 2.0 at least) is that you cannot have PRIVATE members, or protected, it must be public. This makes some sense, but sometimes you wish you could simply declare stuff as private or protected.