Joona I Palaste said:
Isn't that exactly what xarax did in the above code?
However, I'd write it the following way:
public interface A {
public Number g();
}
public interface B {
public Number g();
}
public class C implements A, B {
public Number g() {
if (/* some condition */) {
return new Integer(12);
}
else {
return new Double(20.5);
}
}
}
Note that explicitly casting the returned object reference to a
superclass type is usually not needed. In fact I have written code
similar to the above and only had to use upcasting in a ?: expression
where neither of the returned references was a supertype of the other.
I was writing extremely verbose example so that
the casual/newbie reader could see what was happening.
Also, I come from a Structured Programming background
(from the days before Object Oriented Programming), so
I always insist that my code have only one "return"
statement. Your mileage may vary.
btw: One of the nice things about Number is that
the caller doesn't really need to use "instanceof",
because it has the various methods for extracting
the value as various primitives. So, just use the
Number instance without caring about the actual
subtype. (Polymorphism is fabulous.)