It's not a secret anymore!*
The moose likes Beginning Java and the fly likes interface implementation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "interface implementation" Watch "interface implementation" New topic
Author

interface implementation

gayathri mukkavilli
Greenhorn

Joined: Mar 09, 2005
Posts: 20
Hi,

Suppose "Product" is an interface and "ProductImpl" is the class which implements "Product" interface which consists of a constructor
ProductImpl();

Then what does the following statement means
Product prod = new ProductImpl();

Can we give ProductImpl prodimpl = new ProductImpl() ???
what is wrong with the above statement?
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61763
    
  67

Moved to Java in General (beginner)


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Stuart Gray
Ranch Hand

Joined: Apr 21, 2005
Posts: 410
Both of the lines you have written are accepted by the compiler. The advantage of this:

is that you can use any Product implementation. For example, maybe you have class Soda that implements Product, and class Cheese that also implements Product. You could write both of these two lines, and the compiler would allow them, because both classes 'are' products:

Then presuming that the Product interface has a getPrice() method, we can do this:


Now, a real advantage of this is that if we define another Product implementation later, say Cigarette, we could slot that into the code at the definition line, and all would be well:

We would not have to change any other code because the compiler simply expects a product, and that is what we have given it. We know that the getPrice will still work because all Products have this method, and Cigarette is a product.

Being able to change the exact implementation like this is known as Polymorphism and is one of the inherent advantages of interfaces.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Duplicate of topic in SCJP

Please answer there.


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: interface implementation