Computer Science Canada

Odd problem with generics in Java 1.7

Author:  matt271 [ Mon Sep 17, 2012 11:32 am ]
Post subject:  Odd problem with generics in Java 1.7

Hi,

I am having an odd problem with generics in Java 1.7. As I am not admin on this current computer, I cannot install 1.6 and test if it is a problem there too.

Basically, I have some interface called MyInterface, and some class called MyClass that implements MyInterface. Then I have a method myMethod that takes a parameter of some generic instance of MyGenericClass<MyInterface> and I want to pass it an instance of MyGenericClass<MyClass> is this possible?

The setup is like:
public interface MyInterface;
public class MyClass implements MyInterface;
public class MyGenericClass<T>;

public void myMethod(MyGenericClass<MyInterface> ditto);

and the problem is I cannot state:
myMethod(new MyGenericClass<MyClass>());

My question is why does this not work? Is this something you cannot do in java? Is something different in Java 1.7?

I know I can say

MyInterface bleh = new MyClass();

So what is the difference to putting an instance of MyClass into a generic method expecting a MyInterface? I think if this is not possible, it would not make sense to allow a generic type of an interface?

Thank You

Author:  DemonWasp [ Tue Sep 18, 2012 1:07 am ]
Post subject:  RE:Odd problem with generics in Java 1.7

In general, Parameterized<C> is not an instance-of (instanceof operator) Parameterized<I >, even when C implements I, or C extends I.

The full explanation for the reason behind this behaviour is a little involved, and is explained here: http://docs.oracle.com/javase/tutorial/java/generics/subtyping.html


: