Can somebody explain why we have interfaces in programming languages? For instance, in Java:
public interface SomeFunction
{
public void doSomething();
}
public class SomeOtherFunction implements SomeFunction
{
public void doSomething()
{
System.out.println("Some output.");
}
}
It just seems like a lot of extra work to come up "interfaces". What's the purpose? How is this different from other forms of inheritance in a language like C++ (virtual functions, overriding, etc)? It seems like the sole purpose of an interface is to regulate
the input/output/functions of an object and nothing else. And maybe that is their only purpose...sort of like enforcing a standard that can be used across several different object types.
I'm just wondering how useful such a feature has been.
-
-
Cornelius Ellsonpeter wrote:
Can somebody explain why we have interfaces in programming languages? For instance, in Java:
public interface SomeFunction
{
public void doSomething();
}
public class SomeOtherFunction implements SomeFunction
{
public void doSomething()
{
System.out.println("Some output.");
}
}
It just seems like a lot of extra work to come up "interfaces". What's the purpose? How is this different from other forms of inheritance in a language like C++ (virtual functions, overriding, etc)? It seems like the sole purpose of an interface is to regulate the input/output/functions of an object and nothing else. And maybe that is their only purpose...sort of like enforcing a standard that can be used across several different object types.
I'm just wondering how useful such a feature has been.
I think so you can overload or pass results to it via the interface and not the action function...For instance....
public interface SomeFunction
{
public void doSomething(variable result);
}
where if your function can accept a result it saves you from having to overload the result and create other funtions to pass it on...
public void doSomething()
{
System.out.println("Some output.", variable result);
}
However I could be wrong....(probably am)
-
On a conceptual level, the difference between an interface and a base class is the difference between "can-do" and "is-a". The Windows Forms Button class inherits from Control, because it "is-a" control. It implements the IDisposable interface because it "can-do" dispose.
On a practical level, there isn't much difference between an interface and an abstract base class. For example C++ has no real interfaces, but you can get exactly the same effect by having a class with only abstract methods. There's no functional difference between that and a proper interface.
The reason Java and C# do have a separate interface construct is because unlike C++, they don't support multiple inheritance. Multiple inheritance, while powerful, has a whole host of problems (like if class B and C both inherit class A, and class D inherits both C and B, D is inheriting A twice, how do you deal with that?).
So whereas Java and C# allow a class to have only one base class, it can implement multiple interfaces. That's the reason why they're separate: you can still allow multiple interfaces without getting into the hornet's nest that is multiple inheritance. -
I saw that in a book...with similiar language (where they used the "is a" vs. the "has a" concept.Sven Groot wrote:On a conceptual level, the difference between an interface and a base class is the difference between "can-do" and "is-a". The Windows Forms Button class inherits from Control, because it "is-a" control. It implements the IDisposable interface because it "can-do" dispose.
That's why I'm struggling...it seems rather useless if you think about it.Sven Groot wrote:On a practical level..."
I agree. But I haven't seen a whole lot of "multiple inheritance" examples in the things I've seen, but that doesn't mean anything either.Sven Groot wrote:The reason Java and C# do have a separate interface construct is because unlike C++, they don't support multiple inheritance. Multiple inheritance, while powerful, has a whole host of problems (like if class B and C both inherit class A, and class D inherits both C and B, D is inheriting A twice, how do you deal with that?).
But why even have it at all then? Why not create the functions as needed in the class? Unless it some sort of a "regulation" type thing, where you force objects to conform to a particular interface in the interest of enforcing consistency of some sort.Sven Groot wrote:So whereas Java and C# allow a class to have only one base class, it can implement multiple interfaces. That's the reason why they're separate: you can still allow multiple interfaces without getting into the hornet's nest that is multiple inheritance.
I'm not sure either...I guess I haven't used enough Java to really get a handle on its "best practices".Cybermagellan wrote:where if your function can accept a result it saves you from having to overload the result and create other funtions to pass it on... -
well at least in part it goes like this:
an "interface" is like a contract or a blueprint.
it describes the "thing" in general terms.
one example is you want to write a "plugin" for an app...
think for a minute of how the app can possibly load and run a plugin that was not even written at the time the app was compiled ?
if the creator of the app defines an interface that says: you need to have the following properties and methods, I will call method x to 'start' you and then....
then the plugin author has a plan to follow and can write that plugin. and so can others....
so that's one way they help.
also if you have more than one group working on a large program interfaces can give each group a model of what each part will look like / work like so they can work on one part and later they can all join up and work as a whole.
if two parts do not work then you see if one or both have failed to follow the interface spec.
that tends to help control the process and the changes. -
Good points...I didn't think of some of that...the whole "joining the parts up later on" bit makes sense. I guess I was thinking of designing on an individual basis (writing a project for yourself) rather than writing for a team. But how often is the whole plugin concept used? I can see it with Eclipse maybe or some other things...and maybe nobody has really made a lot of use out of it (yet) in other languages like C#.
I suppose I could e-mail Anders Hjeilsberg or James Gosling and ask, if I can't find it in a book somewhere. As long as I don't start out by writing, "Interfaces are so stoooopid. James, you're a dork!" I just might get an answer. -
Interfaces allow another level of poylmorphism, especially in languages that do not support multiple inheritance. While you cannot construct Interface "object" directly, you can refer to an object by an interface that the class implements. For example:
class Car : IVehicle {}
class Airplane : IVehicle {}
IVehicle[] myGarage;
.
.
.
myGarage[0] = new Car();
myGarage[1] = new Airplane();
From here I can loop through myGarage and call any method that IVehicle implements.
You could make IVehicle a base class, but in this case, the "Go" method would be radically different, so you wouldn't really save any work.
And as others have said, it's really an "is a" vs. a "can do" or "supports" philosophy. Think of an Interface as a contact a class can implements that says "I support this functionality, reguardless of whay my concrete implementation is." This allows you a lot of power to model your software more like the real world, since concrete object in wildly different class hierarchies may have some functionality in common that they support. An interface allows you to act against both of those object without haveing to worry about their concrete implementation.
When you program, it's better, IMHO, to program to the interface of an object you wish to use, not the object itself. I tend to think as interfaces as API's for objects, with the philosophy that the underlying object can (and will) change, the but the inerface should be static.
Hope this helps. -
You can also take a bunch of different classes that implement the interface and make calls to the methods in the classes through the interface (polymophic). That's pretty cool if you want a collection of objects and want to operate on them without figuring out what they are for a type. And again you aren't bound to an inheritance model to get the functionality.
-
Cornelius Ellsonpeter wrote:
But why even have it at all then? Why not create the functions as needed in the class? Unless it some sort of a "regulation" type thing, where you force objects to conform to a particular interface in the interest of enforcing consistency of some sort.
Sven Groot wrote: So whereas Java and C# allow a class to have only one base class, it can implement multiple interfaces. That's the reason why they're separate: you can still allow multiple interfaces without getting into the hornet's nest that is multiple inheritance.
yes . it can be used to enforce some standard such as function signatures .
example for the windows desktop search they provide some interfaces which can be implemented to extend the type of files that can be indexed. now when the funtion/method signature is standard the desktop search which identifes these methods based on signatures can easily call them like a plugin .
-
looks like jb43081 and I are on the same page

-
Cornelius Ellsonpeter wrote:But why even have it at all then? Why not create the functions as needed in the class?
Interfaces tell the consumers of your class that your class can do something. It enables people to write functions/classes that can operate on everything that exposes a certain funtionality.
For instance, I could write a function that randomizes a list:
void RandomizeList(ArrayList list)
And I put that in a library. But what if some application wants to use my function, but they're not using an ArrayList. Maybe they're using .Net 2.0 and are using a List<T>. Or they're using a regular array. Or a custom strongly typed collection. Or maybe they're using a LinkedList<T>. All those people are out of luck, despite the fact that all my RandomizeList function probably uses is the Length and Item properties, and all those classes have those properties. But because I wrote my function so it takes an ArrayList, they can't use it.
Interfaces are a way out. In object-oriented terminology, an interface is a "contract". It's a guarantee made by a class that they have certain methods that behave a certain way (the compiler unfortunately can't check the last part; I can easily implement a Length property for a collection that doesn't in fact return the length. The ability to specify and statically verify a semantic contract is somewhat of a holy grail for software engineers). By implementing the IList interface on a class, I'm saying "this here class behaves itself like a list of items, it has these methods and they (should) behave as you would expect for a list of items".
I can then write my RandomizeList method as follows:
void RandomizeList(IList list)
By that I'm saying "this method can randomize a list, any list. It doesn't matter how it stores that list (array, linked list, a database, or subspace for all I care), as long as it behaves like a list to me, and does what a list can do, I can randomize it". And now, everybody can use my function, regardless of what type of list they're using, as long as those lists implement IList.
That's the point of interfaces. I hope that clears it up a little.
-
jb43081 has it right. It might be helpful to look through MSDN's .NET class libraries to see how they use interfaces.
Interfaces are really useful once you grasp them. For instance, if I encounter a class writen by some 3rd party and I see they've implemented certain well-known interfaces, that gives me hints about how I'm expected to use the class.
So if I see that it implements IEnumerable and ICollection, I don't have to wonder about how to loop through each of the objects in the collection. I use it the same way I'd use any other class that implements those interfaces. -
Thorny question here...so, by keeping the interfaces the same, could you technically get around some forward/backward compatibility issues that could crop up as libraries/programs evolve? I haven't been paying a whole lot of attention to the various iterations of Java/C#, but have the interfaces changed as often as the available functions/objects themselves?jb43081 wrote:When you program, it's better, IMHO, to program to the interface of an object you wish to use, not the object itself. I tend to think as interfaces as API's for objects, with the philosophy that the underlying object can (and will) change, the but the inerface should be static. -
Not to mention Interfaces are currently the only way C# allows for multiple inheritence allowing for a Car class to implement IVehicle and ISedan for instance.
-
Just a note, Interfaces are used extensively in Test Driven Development (TDD), like the Agile methodology.
-
If you need a real world example think of USB "interfaces" on your PC. Manufacturers of peripherals have agreed to support the USB interface so that not every computer manufacturer has to provide a different interface for each peripheral. So if a peripheral "implements" the USB interface the computer instantly knows that it will work without having to know what specific peripheral it is (the specific type of peripheral is abstracted away).
A nice example in C# is the IEnumerable interface. Every class that implements IEnumerable can be used with the foreach command. foreach doesn't have to know if the collection over which it iterates is actually a List, an Array or a DataTable. -
Sven,
strictly speaking there is a fundamental difference between abstract classes and interfaces: you can add implementation to an abstract class and not break consumers of the class. Clearly, this is not the case with interfaces as they can only be abstract and require that a consumer implement each member.
So, an interface is a strict contract that is immutable whereas an abstract class offers the ability of the class author to add implementation (not new abstract members) without breaking implementors who already use the class.
C -
Cornelius Ellsonpeter wrote:
Thorny question here...so, by keeping the interfaces the same, could you technically get around some forward/backward compatibility issues that could crop up as libraries/programs evolve? I haven't been paying a whole lot of attention to the various iterations of Java/C#, but have the interfaces changed as often as the available functions/objects themselves?
jb43081 wrote: When you program, it's better, IMHO, to program to the interface of an object you wish to use, not the object itself. I tend to think as interfaces as API's for objects, with the philosophy that the underlying object can (and will) change, the but the inerface should be static.
Interfaces help in abstracting a situation, and when fixing bugs this help a lot. That doesn't mean that Interfaces are sacred - sometimes you have to break an interface because there are drastic changes in requirements. In order to prevent breaking interfaces, you should design them as simple as possible.
Rotem
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.