• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

interface implementation

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Sheriff
Posts: 67746
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Moved to Java in General (beginner)
 
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Duplicate of topic in SCJP

Please answer there.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic