File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Why java Interface? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Why java Interface?" Watch "Why java Interface?" New topic
Author

Why java Interface?

Srinivas Katta
Ranch Hand

Joined: Feb 01, 2007
Posts: 76
Hi All,

We can feel the advantages of class inheritance from at least sharing and reusing the super class's methods. But in an interface, there are only abstract methods, and we have implement all the methods in the class that implements this interface, why do we still use interface? Why don't we define the methods and write their code directly in the class without implementing any interface or something like that? In other words, what are the advantages of using interface? I have read
some books, in which the authors just say it's a protocol and so on. I still can not understand the necessity of using interface. Can anybody give me a sample to illustrate this?

Thanks
Srinivas
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

OO programming talks about behaviour, and Interfaces define behaviour without specifying how that behaviour is implemented.

In a simple sense, consider the java.lang.Thread Class and the java.lang.Runnable Interface.
Java does not allow multiple inheritance, some once you have a base concrete class you're stuck with it. Therefore any class that wanted to run would be forced to extend Thread and also it would not be possible to make other classes that do no already extend Thread to be able to run.

The Collections classes make heavy use of Interfaces so that you can swap one Collections implementation for another easily. If you force users to Pass ArrayLists to your methods than that works fine until someone wants to use a Vector, LinkedList, stack or even a class of their own.

The JDBC API makes even heavier use of interfaces by defining database operations in terms of interactions between interfaces without very few concrete classes. This allows Driver writers to hide the concrete implementation under the interfaces and as long as they behave in the manner defined you never need to know the difference.

This just scratches the edge, but by defining code in terms of behaviour and not concrete implementations you provide looser coupling between the parts and open yourself up to greater flexibility in the future.
Srinivas Katta
Ranch Hand

Joined: Feb 01, 2007
Posts: 76
Thanks a lot for the Detailed explanation
 
GeeCON Prague 2014
 
subject: Why java Interface?