This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

interface implementation

 
gayathri mukkavilli
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 64700
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moved to Java in General (beginner)
 
Stuart Gray
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Duplicate of topic in SCJP

Please answer there.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic