File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Doubt on interface" Watch "Doubt on interface" New topic
Author

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
Bartender

Joined: Jun 06, 2007
Posts: 2711
    
    5

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


SCJP, SCWCD.
|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
Marshal

Joined: Mar 22, 2005
Posts: 39547
    
  27
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 ]

Ping & DNS - updated with new look and Ping home screen widget
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

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


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt on interface
 
Similar Threads
Interface questions
interface problem
Interface
Interface
public modifier