tags:

views:

121

answers:

4

Hello, I am still not so familiar with interfaces in Java. I know that interface tells which methods should have classes that implements that interface. But what is sense? Why to use it? Is not easier to create instance of class that implements interface instead of instance of interface? Or do I something important miss?

+1  A: 

Java does not support multiple inheritance, but it does allow a single class to implement multiple interfaces.

This makes it possible to define functionality in terms of the expected "contract" a class should fulfil, i.e. "it must be enumerable, it must be serializable, and so on", rather than "it must be of this particular type".

unwind
+2  A: 

Try reading about "programming to an interface" and "inversion of control".

Konrad Garus
A: 

Many people use interfaces to define abstract classes - all the members of a class, without the explicit implementation. I frankly don't see a lot of value in that.

I prefer to use interfaces to do one of two things:

  1. Show the orthogonal capabilities of a class
  2. Declare the requirements that a class has

The second one is, I think, the more interesting, and probably deserves more explanation. You might write a class that requires teh ability to load or save some data. Rather than directly talking to whatever data store you'll use, you can declare an interface that has the methods you want to be able to call.

Then, implement a class that has those methods (implements that interface), and pass it to the class that wants it.

This gives you good abstraction and separation of responsibilities.

kyoryu
+1  A: 

An interface is essentially a contract guaranteeing that a given class will have the listed set of methods.

This allows you to just say that you have an object which happens to oblige to "List"-contract, so you know you have e.g. a "size()" and an "add(...)" method, which you can then just call.

This may allow you to hide immense amounts of complexity behind a simple interface. Just think of JDBC Connections...

Thorbjørn Ravn Andersen