generics, inheritance, and subtypes
As you know, you can assign one type of object to another, as long as they are compatible. For example, you can assign an integer object to a value of object .
Object someobject = new Object (), Integer someinteger = new Integer (ten), someobject = Someinteger; Ok
In object-oriented technology, this is referred to as the "is a" relationship. That is , an integer is an Object in which the assignment is allowed. Again, the following code snippet is valid:
public void SomeMethod (number N) {/* ... */}somemethod (new Integer); Oksomemethod (New Double (10.1)); Ok
The same principle applies to generics:
box<number> box = new box<number> (); Box.add (new Integer); Okbox.add (New Double (10.1)); Ok
Limitations consider the following method:
public void Boxtest (box<number> n) {/* ... */}
Now consider what type of parameter this method accepts? Its signature tells us that it only accepts a single parameter box<number>.
What does that mean? Can we box<integer> or box<double>? The answer is in the negative. Because they are not sub-types of box<number>.
This is a common misconception in generic programming, which is a very important concept to learn.
Although Integer is A subtype of number, box<integer> is not a box<number> subtype
Note:Any specific type A and B, such asNumber is not relatedto Integer, myclass<a>, and myclass<b>, regardless of whether a and B are related. The common parent class of myclass<a> and Myclass<b> is Object.
When there is a relationship between parameter types, how to establish a relationship between two sub-generic classes like subtypes, refer to wildcard characters and subtypes.
Generic class and sub-type
You can either extend or implement it by using a subclass or interface. The relationship of a type parameter of a class or interface to the type parameter of another class or interface, as determined by the extended or implemented statement.
Use the collection class collections to do An example: arraylist<e> implements list<e>;list<e> Inheritance (Extended) collection<e>.
Therefore,arraylist<string> is the list<string> subclass,list<string> is collection<string> Sub-class. As long as the type parameters are not changed, their subtype relationships are not becoming.
Collections System Example
Now suppose we want to define our own list interface Payloadlist, which associates a generic type P value and with each element. The declaration may appear to be:
Interface Payloadlist<e,p> extends list<e> { void setpayload (int index, P val); ...}
below the payloadlist of the list<string> are sub-typed:
- Payloadlist<string,string>
- Payloadlist<string,integer>
- Payloadlist<string,exception>
Payloadlist System Example
Original Address https://docs.oracle.com/javase/tutorial/java/generics/inheritance.html
Java Generics generics---the third part generics, inheritance, and sub-types