Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this self-referential Generics assignment illegal?

Tags:

java

generics

I am having a hard time understanding why the error below happens. If #1 is ok, why is #2 not?

public interface IFoobar<DATA extends IFoobar> {
    void bigFun();
}

class FoobarImpl<DATA extends IFoobar> implements IFoobar<DATA> {
    public void bigFun() {
        DATA d = null;
        IFoobar<DATA> node = d;    //#1 ok
        d = node;                  //#2 error
    }
}
like image 718
marathon Avatar asked Apr 18 '12 03:04

marathon


People also ask

What is the purpose of generics?

The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types. An entity such as class, interface, or method that operates on a parameterized type is a generic entity. Why Generics?

What is the use of self referential structure?

Self-referential structure plays a vital role in the linked list, trees, graphs, and many more data structures. By using the structure, we can easily implement these data structures efficiently. For defining a particular node, the structure plays a very important role.

What is generics in Java?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc, and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types. An entity such as class, interface, or method that operates on a parameterized type is called ...

What is generics in C++?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.


2 Answers

Because DATA is a type of IFoobar, but not the other way around. It's no different than:

String d = null;
Object o = d;                //#1 ok
d = o;                       //#2 error
like image 200
mellamokb Avatar answered Oct 08 '22 18:10

mellamokb


Because the compiler knows that the DATA type implements IFoobar. But it doesn't know that all IFoobar objects are actually DATA objects. Simply having DATA as a generic parameter doesn't mean anything; you could just as well implement another unrelated class that implements IFoobar<DATA>.

like image 39
John Calsbeek Avatar answered Oct 08 '22 19:10

John Calsbeek