How to override a method with different return type

S

sandy

hi all,
To begin with i thank the creaters of this group.
I am new java world and facing a new challenge.
i have a method in class A named
protected int foo(int args) { /* ..... */ }
and have a class B that extends class A and would like to have a
method foo in it which overrides it as
public double foo(int args) { /*........*/}
i need something like above code, i.e the return type be different ,
can anybody help me on this

thanks
sandy
 
J

J. Verdrengh

i have a method in class A named
protected int foo(int args) { /* ..... */ }
and have a class B that extends class A and would like to have a
method foo in it which overrides it as
public double foo(int args) { /*........*/}

This is not allowed in Java. And if it were allowed, the return type of the
overriding method (double in your case) should be 'more specific' then the
return type of the overriden method (int in your case). After all a subclass
should obey the contract of its superclass. So if the return type of the
overriden method is double, it would be legal (from a object-oriënted
programming point-of-view) to override it with a method returning a int
(since each int can be implicitly casted to a double). But again: none of
this is possible in Java.
 
S

sks

J. Verdrengh said:
This is not allowed in Java. And if it were allowed, the return type of
the overriding method (double in your case) should be 'more specific' then
the return type of the overriden method (int in your case). After all a
subclass should obey the contract of its superclass. So if the return type
of the overriden method is double, it would be legal (from a
object-oriënted programming point-of-view) to override it with a method
returning a int (since each int can be implicitly casted to a double). But
again: none of this is possible in Java.

You can do that with Object types (not primitives) in 1.5
 
R

Roedy Green

You can do that with Object types (not primitives) in 1.5
and the overriding type has to be more specific, e.g. base returns
Dog, override always returns Dalmatian, not the reverse. Dalmatian
is still a Dog.

You can't break the contract of the original base class.
..
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top