S
Stefan Ram
When someone asked me "When is an explicit upcast needed?",
I responded with the expression
Math.random() > 0.5 ?( Object )System.in : System.out
Bue in Java 1.5 this upcast is not required anymore. So, the
expression
Math.random() > 0.5 ? System.in : System.out
will compile under 1.5 and 1.6, but not under 1.3 and 1.4.
So what would be an example of a situation where an explicit
upcast of an expression with a reference type is required
under Java 1.5 and 1.6?
Preferably an example that uses standard methods and
identifiers as above and does not require the declaration
of additional identifiers [methods].
I can think of:
interface A {} interface B {} class C implements A,B {}
public class Main
{ static void f( A a ){}
static void f( B b ){}
public static void main( final java.lang.String[] args )
{ f(( A )new C() ); }}
Here the upcast "( A )" is required.
However, this example needs to declare methods and a
situation with two interfaces (multiple inheritance),
I would prefer an example with a single class as the
super type (single inheritance) and without the need
to declare additional classes or methods.
I responded with the expression
Math.random() > 0.5 ?( Object )System.in : System.out
Bue in Java 1.5 this upcast is not required anymore. So, the
expression
Math.random() > 0.5 ? System.in : System.out
will compile under 1.5 and 1.6, but not under 1.3 and 1.4.
So what would be an example of a situation where an explicit
upcast of an expression with a reference type is required
under Java 1.5 and 1.6?
Preferably an example that uses standard methods and
identifiers as above and does not require the declaration
of additional identifiers [methods].
I can think of:
interface A {} interface B {} class C implements A,B {}
public class Main
{ static void f( A a ){}
static void f( B b ){}
public static void main( final java.lang.String[] args )
{ f(( A )new C() ); }}
Here the upcast "( A )" is required.
However, this example needs to declare methods and a
situation with two interfaces (multiple inheritance),
I would prefer an example with a single class as the
super type (single inheritance) and without the need
to declare additional classes or methods.