0

Possible Duplicate:
Why should the interface for a Java class be prefered?

I read in a book that It’s poor style to expose the implementation, so:

Good: Set s = new HashSet( );

Fair: HashSet s = new HashSet( );

can you explain why this is?

Community
  • 1
  • 1
user133466
  • 3,391
  • 18
  • 63
  • 92

1 Answers1

0

You should always program to an interface and not to an implementation. This allows loose coupling.
For instance if you replace HashSet to a TreeSet in the first case your code will not be affected. Compare such a change with the second case.
So you would be able to switch implementations without affecting client code as long as client code uses the interface instead of the concrete type.

Cratylus
  • 52,998
  • 69
  • 209
  • 339