According to the Generics trial,
This section states:
Given two concrete types A and B (for example, Number and Integer),
MyClass<A>
has no relationship toMyClass<B>
, regardless of whether or not A and B are related. The common parent ofMyClass<A>
andMyClass<B>
is Object.
Yet, here we're told,
Although Integer is a subtype of Number,
List<Integer>
is not a subtype ofList<Number>
and, in fact, these two types are not related. The common parent ofList<Number>
andList<Integer>
isList<?>
.
Why isn't the parent of MyClass<A>
/ MyClass<B>
in the first example MyClass<?>
? What is the distinction?
A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.
Generic classes encapsulate operations that are not specific to a particular data type. The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees, and so on.
You cannot inherit a generic type. // class Derived20 : T {}// NO!
Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces.
I think the answer is rather trivial. While the correct parent of MyClass<A>
and MyClass<B>
is indeed MyClass<?>
, the tutorial did a small simplification there, as wildcards have not been introduced yet.
The point of saying
The common parent of
MyClass<A>
andMyClass<B>
isObject
.
was just to make it clear that none of the two types is the parent of the other, regardless of the relationship between A
and B
.
This is confirmed by the following comment right below your first quote:
For information on how to create a subtype-like relationship between two generic classes when the type parameters are related, see Wildcards and Subtyping.
as well as by the introduction of the chapter Wildcards and Subtyping:
As described in Generics, Inheritance, and Subtypes, generic classes or interfaces are not related merely because there is a relationship between their types. However, you can use wildcards to create a relationship between generic classes or interfaces.
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