Basic stupidity Java generics

P

pjvleeuwen

Hi all,
Probably I am doing something very twisted, but I keep getting an
"incompatible types" compile error and I don't know why. I brought it
back to the very simple script below. Could somebody please explain
me, why is this incorrect, it seems perfectly logical to me... :(
This is a big problem for me, because I want to hide all
implementation behind interfaces, and I need the return type
IContainer<Ithing> to be compatible with Container<Thing>. Apparently
it isn't.
Anyone? Many things for any help!
Cheers,
Paul


public class Test {
public interface IThing {
}
public interface IContainer<TYPE extends IThing> {
}
public class Thing implements IThing {
}
public class Container<TYPE extends Thing> implements
IContainer<TYPE> {
}
public Test() {
IContainer<IThing> var = new Container<Thing>();
}
public static void main(String[] args) {
new Test();
}
}


$ javac Test.java
Test.java:23: incompatible types
found : Test.Container<Test.Thing>
required: Test.IContainer<Test.IThing>
IContainer<IThing> var = new Container<Thing>();
^
1 error
 
P

pjvleeuwen

Damn! sorry, I found the problem. I spend two hours before posting the
question and I found the answer just minutes after the posting:
This is not correct: IContainer<IThing> var = new Container<Thing>();
It needs to be: IContainer<? extends IThing> var = new
Container<Thing>();

Again, sorry, and thanks for reading.

Cheers,
Paul
 
R

Roedy Green

public interface IContainer<TYPE extends IThing> {
public class Container<TYPE extends Thing> implements

It is confusing and probably incorrect to redefine the meaning of TYPE
 
L

Lasse Reichstein Nielsen

Roedy Green said:
public class Container<TYPE extends Thing> implements

It is confusing and probably incorrect to redefine the meaning of TYPE

Might be confusing (although I personally don't think so, and would
just have called them both "T"), but it's definitly not incorrect.

It's just two unrelated type variables that happen to have the same
name. It's not more incorrect than having two different methods both
containing a variable called "i", or two methods both having an
argument called "x".

/L
 

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

Similar Threads

generics puzzle 57
Hairy generics question 29
Generics ? 14
Generics inheritance 4
The distinction between a java applet and an application 1
Generics annoyance 18
generics:< ? >vs.< T > 13
help me understand generics 8

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top