Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Confusion in overriding" Watch "Confusion in overriding" New topic
Author

Confusion in overriding

Rajat Sarkar
Greenhorn

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
Sheriff

Joined: Oct 13, 2005
Posts: 37958
    
  22
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Confusion in overriding
 
Similar Threads
e below program is throwing error at compile time --- showVal(int a) can not applied to ()
Specific method call
function overloading and overriding
Can static methods be inherited?
Class Already Defined