
-----------------------------------
matt271
Mon Sep 17, 2012 11:32 am

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 and I want to pass it an instance of MyGenericClass is this possible?

The setup is like:
public interface MyInterface;
public class MyClass implements MyInterface;
public class MyGenericClass;

public void myMethod(MyGenericClass ditto);

and the problem is I cannot state:
myMethod(new MyGenericClass());

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

-----------------------------------
DemonWasp
Tue Sep 18, 2012 1:07 am

RE:Odd problem with generics in Java 1.7
-----------------------------------
In general, Parameterized is not an instance-of (instanceof operator) Parameterized, 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
