• Post Reply Bookmark Topic Watch Topic
  • New Topic

Interface  RSS feed

 
Lovish Setia
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Decoupling interface from implementation allows an interface to be applied to multiple different implementations, and thus your code is more reusable."

Can any one give an example of what the above statement says?
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Connection, PreparedStatement, and ResultSet are all interfaces in the java.sql package. That same code (using interfaces) can work with any one of dozens of databases, and the only thing I have to change is the connection parameters passed to getConnection() in the first line. Each vendor provides their own implementation of those interfaces. I don't know or care anything about the names of the implementation classes or about how they do their jobs. All that matters to me is they meet the contracts set out by the interfaces. That is, the ResultSet implementation will have an executeQuery() method and a next() method.

Another canonical example is the Collections Framework in java.util. I can code to a List without caring whether it's an ArrayList or LinkedList or CopyOnWriteArrayList or whatever. Depending on what I'm doing, I may even be able to code to Collection, without even caring if it's a List or Set or something else.
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You probably won’t need both assignments in the same application.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Think of an interface as the spec that defines what a USB connection looks like. My PC will allow me to plug a phone, a thumb-drive, a printer, or any other of about a billion devices in. All of them basically do the same thing - transmit data. But the specific implementation of what is DONE with that data, and how it is used, is different.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
fred rosenberger wrote:But the specific implementation of what is DONE with that data, and how it is used, is different.

@Lovish: Just one reason to read the WhatNotHow (←click) page.

Winston
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!