Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic class parent

Tags:

java

generics

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 to MyClass<B>, regardless of whether or not A and B are related. The common parent of MyClass<A> and MyClass<B> is Object.

Yet, here we're told,

Although Integer is a subtype of Number, List<Integer> is not a subtype of List<Number> and, in fact, these two types are not related. The common parent of List<Number> and List<Integer> is List<?>.

Why isn't the parent of MyClass<A> / MyClass<B> in the first example MyClass<?>? What is the distinction?

like image 325
wulfgarpro Avatar asked Oct 29 '12 12:10

wulfgarpro


People also ask

What is generic class with example?

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.

What is meant by generic class?

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.

Can generic class be inherited?

You cannot inherit a generic type. // class Derived20 : T {}// NO!

What is a generic class in C#?

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.


1 Answers

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> and MyClass<B> is Object.

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.

like image 128
rolve Avatar answered Oct 17 '22 22:10

rolve