File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Doubt on interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Doubt on interface" Watch "Doubt on interface" New topic

Doubt on interface

abin joy
Ranch Hand

Joined: Jul 29, 2008
Posts: 35
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

Joined: Jun 06, 2007
Posts: 2851

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

|Asking Good Questions|
satishkumar janakiraman
Ranch Hand

Joined: May 03, 2004
Posts: 334
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

Joined: Mar 22, 2005
Posts: 42965
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

Joined: Oct 27, 2005
Posts: 20276

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

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Doubt on interface
jQuery in Action, 3rd edition