Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Possible Duplicate:
When to use abstract classes instead of interfaces and extension methods in C#?
What other reasons are there to write interfaces rather than abstract classes?

This question sounded a bit trivial to me as well, till I gave a it serious thought myself.

What is the point of a Java interface? Is it really Java's answer to multiple inheritance?

Despite using interfaces for a while I never got around to think the point of all this. I know what an interface is, but still pondering on the why.

share|improve this question

migrated from stackoverflow.com Jan 23 '12 at 4:03

This question came from our site for professional and enthusiast programmers.

marked as duplicate by Péter Török, rjzii, ChrisF Jan 23 '12 at 14:11

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

To give people something that forces them to implement all methods the implemented interface guarantees in a uniform fashion in situations where you might be writing an alternate database access layer or set of web services for instance. It doesn't really enable multiple-inheritance, so much as give you a mechanism that forces you to implement multiple-inheritance manually by chaining methods to an instance of whatever it is you're "inheriting" from which could be anything you want for any given method. It's more like an object interface unit test or validation mechanism than anything else. –  Erik Reppen Feb 5 '13 at 18:37

8 Answers 8

Java does allow multiple inheritance of interface; single inheritance is for implementation.

Interfaces are important because they separate what a class does from how it does it. The contract defining what a client can expect leaves the developer free to implement it any way they choose, as long as they uphold the contract.

You see examples of this all over the JDK. Look at the java.sql package - it's riddled with interfaces. Why? So different relational databases can be free to implement those methods for their particular product. Clients need only deal with the interface reference types. Changing relational databases is as easy as swapping one JDBC driver JAR for another. Clients need not change. (As long as they don't stray from the contract.)

Dynamic proxies and aspect-oriented programming depend on interfaces. They can replace the implementation at runtime that way.

share|improve this answer

You program against an interface instead of a concrete implementation in order to make your code flexible.

For example,

You program against IScrewDriver so that you can use PhilipsScrewDriver or FlatScrewDriver, based on your needs.

Usually, you'll use some sort of IoC container to "inject" the appropriate screw driver on your code, but that's not really necessary.

Hope the examples helps.

share|improve this answer
That's not a reason for interfaces, instead of abstract classes. –  DeadMG Jan 23 '12 at 13:10
@DeadMG: an abstract class is like an interface in that it defines a contract and not a particular implementation. Either one works. –  Esteban Araya Jan 27 '12 at 15:43

What is the point of a Java interface?

The point is to separate the API (what to do) from the implementation (how to do it).

Interfaces are also necessary when using callbacks, since Java doesn't allow you to pass function references.

Is it really Java's answer to multiple inheritance?

Among other things, yeah. It gives you some of the features of MI, without the nasty complications.

share|improve this answer

This used to puzzle me until I realized something:

Fundamentally, an interface is simply a class that contains only abstract methods. By making such an entity into an interface you gain some flexibility that you don't have with classes.

share|improve this answer
They may appear this way, but an interface is fundamentally different to an abstract class, because the interface can't contain any implementation details at all. Also, Interface inheritance works slightly differently to classes, in that you can combine more than one interface to specify the interface of a class, or of another interface. This is commonly called multiple inheritance, but is technically more to do with multiple type compatibility than strictly about inheritance itself. –  S.Robins Jan 23 '12 at 10:48
@S.Robins: As I said, you gain some flexibility--things like multiple inheritance. –  Loren Pechtel Jan 23 '12 at 18:19

There are many reasons why Java has it's own construct for multiple inheritance, i.e. with interface and abstract classes. Here are three that I can think of:

It reduces boilerplate code (i.e. pure virtual functions)

In languages that don't have the interface construct, you have to do a lot of boilerplate coding. Consider in C++ you need to create a class that have pure virtual functions:

class MyInterface
  virtual void show() = 0;
  virtual int number() = 0;

class ConcreteImpl : public MyInterface
  void show()
    cout << "Concrete Impl here";
  int number()
    return 1337;

The equivalent in Java would be less verbose, mostly because methods are virtual (overridable) functions. And it is more apparent that one of the artifacts is the interface.

interface MyInterface {
  void show();
  int number();

class ConcreteImpl implements MyInterface {
   public void show() {
     System.out.println("Concrete Impl here");
   public int number() { return 1337; }

Java does allow a class with mixed pure virtual and implementation, with the abstract keyword.

It constrains the "diamond inheritance" problem

One of the problems associated with multiple inheritance is the hairy diamond inheritance problem. Consider if you have a language that allows this chain of classes in a language such as C++:

Diamond inherted class

Think of a SuperBaseClass that has two implemented BaseClass, both implementing the SuperBaseClass's method as virtual functions. In turn both BaseClass's are implemented by the MyImplementation class. Consider what will happens if you call super() in MyImplementation.draw()? It is not always apparent what will happen, even in C++, developers who have designed this will find themselves in a weird debugging session.

There is nothing particular wrong with diamond inheritance, so to avoid the problems of calling the super-method, you have to design them either by using pure virtual functions or design them in a smarter fashion. In Java, since all methods are virtual by default, you are constrained by the fact that you can only do multiple inheritance with interfaces since they don't contain any implementation (with the implements keyword). Other classes, even abstract ones, can only be single inherited (with the extends keyword).

Seasoned devs were already using interfaces as a concept (circa 1995)

If you got into Design Patterns by GoF, you will notice that they rely heavily on interfaces to design extensible systems. In fact one of the principles of Design Patterns is:

"Program to an 'interface', not an 'implementation'." (Gang of Four 1995:18)

Interface in the GoF sense means that you should program towards a superclass rather than the implementation. One example would be that you should prefer typing your variable to Collection<T>, Iterable<T>, or List<T> instead of ArrayList<T> in Java if the only methods you use on the object is to iterate it. A pattern example from GoF would be the strategy pattern where the context doesn't need to know the exact strategy it is given to execute, but will execute the set one, regardless of what it was.

share|improve this answer

Found this link to be really useful. Couple of excerpts that made sense to me:

...Separation of interface and implementation is one of the primary ideas behind Java in general. The Java virtual machine (JVM), for example, is an abstract computer that defines the way your program "interfaces" with the underlying real computer. A JVM that runs on Windows is one implementation of that abstract computer. A JVM that runs on the Macintosh is another. A JVM that runs on your wristwatch is yet another

Interfaces give you more polymorphism than singly inherited families of classes, because with interfaces you don't have to make everything fit into one family of classes.

By using interfaces, you decouple the parts of your system from each other and generate code that is more flexible: more easily changed, extended, and customized.

share|improve this answer
Welcome to Programmers! Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference. –  Yannis Rizos Jan 23 '12 at 11:16
Have edited the response! –  hakish Jan 23 '12 at 11:32

A implements B, C is not same as A extends B, C

Although it looks pretty clear, I, too, have always been confused when people say interfaces are answer to the lack of multiple inheritance.

As this link shows there are ways to simulate multiple inheritance while using interfaces. But interface is not directly helping implement multiple inheritance.

Interface, I believe, is for multiple subtyping. In the above example, A is both of type B and C. Hence A can be substituted for either members of B or members of C (see this Wikipedia article).

Since you could have multiple implementations of a single interface, it also helps in dynamic polymorphism. Your code depends on the type (the interface) and not on implementation (which could be substituted dynamically based on context).

share|improve this answer
+1, and more if I could simply for mentioning that interfaces are to do with multiple sub-typing instead of inheritance. I get tired of hearing the argument that "interfaces can inherit from many interfaces and therefore expresses multiple inheritance". It's sadly a very common misconception –  S.Robins Jan 23 '12 at 14:29

Yes, interfaces are Java's answer to multiple inheritance. There is absolutely nothing that an interface can do that an abstract class cannot do, except for the fact that multiple interfaces can take part in the ancestry of a class, while multiple classes cannot.

So, we use an interface instead of an abstract class in order to give descendants the freedom to extend whatever base class they wish, (and implement our interface,) rather than forcing them to extend a specific base class.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.