Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Odd problem with generics in Java 1.7
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
matt271




PostPosted: 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
Sponsor
Sponsor
Sponsor
sponsor
DemonWasp




PostPosted: 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, 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
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 2 Posts ]
Jump to:   


Style:  
Search: