permaculture playing cards*
The moose likes Beginning Java and the fly likes code to interface type Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "code to interface type" Watch "code to interface type" New topic
Author

code to interface type

Raj chiru
Ranch Hand

Joined: Aug 12, 2008
Posts: 141
Hi...
Anybody explain to me what is benefit By coding to an interface?
Komal Amaresh
Ranch Hand

Joined: Oct 06, 2008
Posts: 67
it helps promote reusability.

komal
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11153
    
  16

if you code to an interface, then the underlying object can be changed to a different object type, as long as that new type still implements the interface.

Example: we each purchase a class called 'searchTool' from a 3rd party that does some searching. it implements the 'searchList' interface.

You write your code to specifically use the 'searchTool'. You call it's methods directly, access specific parts, and use some of it's pieces in your code.

I write my code to use the 'searchList' interface. I ONLY refer to it by the interface name, only use the interface methods.

a year later, they come up with a 'fastSearchTool' class that implements the 'searchList' interface, and it runs 100 times faster. I don't have to change a single line of my code, and I can drop in the 'fastSearchTool' to gain the benefit.

You, however, have to re-write all your code to now use the new class, if you want to gain the benefits. So while I'm sitting on the beach drinking Maitai cocktails, you are in the office, slogging through your code to make your changes.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Brian Legg
Ranch Hand

Joined: Nov 07, 2008
Posts: 488
You, however, have to re-write all your code to now use the new class, if you want to gain the benefits. So while I'm sitting on the beach drinking Maitai cocktails, you are in the office, slogging through your code to make your changes




If only the real world worked like that!


SCJA
~Currently preparing for SCJP6
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11153
    
  16

A coder can dream, can't he?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: code to interface type
 
Similar Threads
Failed to marshal exception problem
When should Servlet utility classes be Servlets and when ordinary Java classes?
How To Call Two Different Classes From the Main Program Using the Same API?
Sortable Collection with indexed properties
exception over RMI