This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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? Add code tags. CR[/edit] [ October 19, 2008: Message edited by: Campbell Ritchie ]
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.