views:

258

answers:

5

I'm currently working my way through Code Complete and the word "interface" keeps popping up! I'm trying to get my head round what an interface is. Can you define the term? Also what actually makes up a "class interface"?

A: 

It's external face to the world. Usually the set of public methods (members) it exposes.

Technically however they would be 2 different things

An interface would be a public contract. e.g.

interface ILogger
{
  void Log(String str);
}

A class would then 'implement' this interface - in a way saying that it provides this functionality

class ConsoleLogger : ILogger
{
  public ConsoleLogger() { ... }
  public void Log(String str)
  {
    Console.WriteLine("Console Logger " + str);
  }
  // private stuff
}

Users of this service / interface do not have to concern themselves with how it is implemented or who is implementing it? By depending on an interface, the actual implementation can be switched at will.

Gishu
+6  A: 

I think a good way to define an interface is as follows

An interface is a contract specifying a set of methods, fields and properties which will be available on any implementing object

The actual implementation from language to language may have funny little differences but the principal holds.

I considered adding implemented interfaces to the list above but left it off because it seemed to be a bit too language specific. I think it's OK though because the end effect is almost the same. Tacking on more interfaces is just adding more methods, fields and properties to the contract.

JaredPar
A: 

Interface is definition of set of methods that class can impelement. It's mostly used for interface polymorphism.

Darth
+3  A: 

In general, an interface is simply "what the class looks like to the rest of the world".

For example, this class in Java:

class MyClass {
  private string data;
  private string Foo() {...}
  public void Bar(string s){...}
}

could be said to have just the Bar function in its interface. Internally it has a few other members, but they're private, so they're not visible to the outside world.

More commonly, interfaces are also specific types in the language, for example in the following, MyClass implements the interface IMyClass:

interface IMyClass {
  public void Bar(string s);
}

class MyClass implements IMyClass {
  private string data;
  private string Foo() {...}
  public void Bar(string s){...}
}

The interface is now expressed in code, so that any time a variable of type IMyClass is expected, an object of type MyClass can be used, because it implements the correct interface.

jalf
+1  A: 

The interface to a class is its "public face" that other classes can see. It separates the the class's implementation from the way it interacts with other classes. That way different implementations can be swapped out and other classes don't need to know anything about what's behind the interface.

An interface can include both data and function members.

emddudley