• 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

Confusion in overriding

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator



In this program 'turnOn()' method is overridden.turnOn() method in 'Heater', returns different type.But in the main method where the turnOn() is called of Heater class, if the returned value is assigned to type Heater it gives error,whereas the return type is declared as Heater in the second turnOn() method.

Can anyone explain this?
[edit]Add code tags. CR[/edit]
[ October 19, 2008: Message edited by: Campbell Ritchie ]
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please use the code button; I have edited your post so you can see how much better it is to read.

You have covariant return types, but you are not using them. You declare the object as an Appliance, so the compiler expects an Appliance as its return type. When you are trying to assign that to a Heater, the compiler thinks it won't work.

Think what would happen if you used this sort of declaration

Appliance aaa = new WashingMachine();
Heater hhh = aaa.turnNo();

That is what the compiler thinks might happen, which is why it has prohibited it. You could try a classcast (Heater) but that is prone to errors too.

By the way, it is bad design to have non-private fields sw, and it is probably bad design to have fields which are not initialised in the constructor.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic