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
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 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 .
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 ]
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).