Downcasting from generic bases

  • Thread starter Christopher Benson-Manica
  • Start date
C

Christopher Benson-Manica

Why isn't this legal?

public class TestIt {
private static class Foo<T> {
}

private static class Bar extends Foo<Integer> {
}

private static void Baz( Foo<?> foo ) {
if( foo instanceof Bar ) { // "inconvertible types" error
}
}
}

And since that's not legal, why exactly does it become legal if the
parameter foo is of the raw type Foo? I clearly don't understand
generics completely and it seems perverse that I can't ask a
superclass if it's an instance of a base class just because of the
generic type paramters.
 
J

Joshua Cranmer

Christopher said:
Why isn't this legal?

public class TestIt {
private static class Foo<T> {
}

private static class Bar extends Foo<Integer> {
}

private static void Baz( Foo<?> foo ) {
if( foo instanceof Bar ) { // "inconvertible types" error
}
}
}

And since that's not legal, why exactly does it become legal if the
parameter foo is of the raw type Foo? I clearly don't understand
generics completely and it seems perverse that I can't ask a
superclass if it's an instance of a base class just because of the
generic type paramters.
Generics are sometimes confusing. Here is why it gives you an error:

private class Foo<T> {
protected T doSomething();
}

private class Bar extends Foo<Integer> {
protected Integer doSomething();
}

foo1 = new Foo<Integer>();
foo2 = new Bar();
foo1.doSomething();
foo2.doSomething();

Erasing the types, the first method will return Object and the second
Integer. Then, foo2's doSomething will become ambiguous in your code.
The return type would become ambiguous because of the cast.

Yes, I know it seems overprotective, but much of generics is like that.
 
T

Tom Hawtin

Christopher said:
Why isn't this legal?

public class TestIt {
private static class Foo<T> {
}

private static class Bar extends Foo<Integer> {
}

private static void Baz( Foo<?> foo ) {
if( foo instanceof Bar ) { // "inconvertible types" error
}
}
}

Works for me! Are you using and old or non-Sun compiler?

There are some confusing wildcard situations where you have nesting of
generic types (Foo<Bar<?>>), but this code should not be a problem.

Tom Hawtin
 
C

Christopher Benson-Manica

Tom Hawtin said:
Works for me! Are you using and old or non-Sun compiler?

No. I mean, yes, but I didn't realize it until just now. Oops! :)
(I was using 1.5.0_06 - did the language spec change or was this
merely a bug that was fixed in a later version?)
 

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,983
Messages
2,570,187
Members
46,747
Latest member
jojoBizaroo

Latest Threads

Top