This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt on interface

 
abin joy
Ranch Hand
Posts: 35
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
AnInterface ai = new AnInterfaceImpl();

where AnInterface is an interface and AnInterfaceImpl is the class which implements AnInterface
Does it make any sense do this?What is the purpose of a statement like this
 
Amit Ghorpade
Bartender
Posts: 2851
10
Fedora Firefox Browser Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes it does make sense because the ISA relation holds.
The purpose is same as that of a ISA relation. The interface type reference can hold objects of any of its implementers.
And this is used in many cases like

This is used to facilitate runtime polymorphism.


Hope this helps
 
satishkumar janakiraman
Ranch Hand
Posts: 334
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This gives you flexibility to your code. In future if you want to create an instance of another class named AnInterfaceImpl1(), you can change it easily by changing your code to


Design perspective, this type writing style is known as Program to an Interface .
 
Ulf Dittmer
Rancher
Pie
Posts: 42966
73
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A good example are method signatures in an API. If you've defined a method

then it's very hard to change the type of the parameter or the return type, if later you discover that some other kind of List or Map would now be more appropriate.

If you had defined it like

then you can accept and return any kind of List/Map that is convenient (maybe a LinkedList instead of an ArrayList).
[ August 24, 2008: Message edited by: Ulf Dittmer ]
 
Rob Spoor
Sheriff
Pie
Posts: 20388
46
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The general idea is, declare something as broad as possible.

For example, go for Number instead of Integer if you don't care what numbers you need.
Also, go for Collection as much if possible. Only use List or Set if you really need the properties of either one (like the indexing or the unique elements).
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic