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
}
}
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?
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.
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 ...
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.
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
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With