Get the tools you need to learn Java skills fast!
Video tutorials, eBooks, hands-on lab exercises, sample code.
Get started
The moose likes Beginning Java and the fly likes Confusion in overriding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Software Craftsman this week in the Agile forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Confusion in overriding" Watch "Confusion in overriding" New topic

Confusion in overriding

Rajat Sarkar

Joined: Sep 07, 2008
Posts: 18

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 ]
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 41601
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.
Have you tried LearnNowOnline?
subject: Confusion in overriding