Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.programmer > #32042
| From | Xue Feng <xf.lotus@yahoo.com> |
|---|---|
| Newsgroups | comp.lang.java.programmer |
| Subject | overriding with different return value type |
| Date | 2015-07-16 21:04 +0800 |
| Organization | Aioe.org NNTP Server |
| Message-ID | <mo8a4l$h99$1@speranza.aioe.org> (permalink) |
According to the JDK manual, overriding requirs that
(1) the same signature
(2) the same return value type
The following example demonstrates it:
class Base{
public int sum(int x, int y){
System.out.println("Int");
return x + y;
}
}
class Ext extends Base{
public double sum(int x, int y){
System.out.println("Double");
return (double)(x + y);
}
}
The overriding sum in Ext returns double, while the overrided sum in
Base returns int. Their return value type are different. So, we get
error message when compiling.
But the other example seems work in different way. The Object class has
a clone() method, and its header is like this:
protected Object clone() throws CloneNotSupportedException
The clone() in Object class returns an Object's instance. Suppose that
there is a class implements cloneable interface:
class Foobar implements Cloneable{
public Foobar clone() throws CloneNotSupportedException{
System.out.println("Foobar");
return (Foobar)super.clone();
}
}
The clone() in Foobar class returns an Foobar's instance. It's obvious
that the two clone() methods have different return value type, but no
error message comes while compiling. I wonder why the clone() method
works in different way.
Back to comp.lang.java.programmer | Previous | Next — Next in thread | Find similar | Unroll thread
overriding with different return value type Xue Feng <xf.lotus@yahoo.com> - 2015-07-16 21:04 +0800
Re: overriding with different return value type Jeff Higgins <jeff@invalid.invalid> - 2015-07-16 10:04 -0400
Re: overriding with different return value type e.d.programmer@gmail.com - 2015-07-16 07:23 -0700
Re: overriding with different return value type Jeff Higgins <jeff@invalid.invalid> - 2015-07-16 11:20 -0400
Re: overriding with different return value type Lew <lewbloch@gmail.com> - 2015-07-16 17:13 -0700
csiph-web