In learning to inherit, we already know that the object of a subclass can be assigned to the object of its parent class, that is, the parent class reference to the subclass object, such as:
1 New Integer (10);
This is actually the is-a relationship in object-oriented programming. Since the code above is correct, in generics, you can also use the following code:
1 Public classBox<t> {2 PrivateT obj;3 4 PublicBox () {}5 6 PublicT getobj () {7 returnobj;8 }9 Ten Public voidsetobj (T obj) { One This. obj =obj; A } - - PublicBox (T obj) { the Super(); - This. obj =obj; - } -}
Call:
1 New Box<>(); 2 Integer i = ten; 3 Double d = 2.3; 4 b.setobj (i); 5 System.out.println (B.getobj ()); 6 B.setobj (d); 7 System.out.println (B.getobj ());
This is correct, because 10, 2.3 of the types are subclasses of number. However, suppose we have the following methods:
1 Public Static void print (box<number> b) {2 System.out.println (B.getobj ()); 3 }
Then we call:
1 New Box<>(); 2 Integer i = ten; 3 b1.setobj (i); 4 print (B1);
The above program is also able to function properly, but if we use the following method to invoke:
1 New Box<>(); 2 b2.setobj (ten); 3 // Compilation failed
This is not compiled. Because, regardless of the relationship between Integer and number, box<integer> and box<number> are not related, the only relationship between them is that they are all subclasses of object. :
(If you want them to have an inheritance relationship, see my next blog post, "Analysis of the use of wildcards in generics")
What about having an inheritance (or implementing interface) relationship between generic classes? Let's take list and ArrayList for example:
By looking at the API documentation, we can see that the ArrayList class is:
1 Public class Arraylist<e>extends abstractlist<e>implements List<e>, Randomaccess, cloneable , Serializable
And the list interface is:
1 Public Interface List<e>extends collection<e>
At this point, we can say that arraylist<string> implementation of the List<string> interface inherits the Collection<string> interface, I believe this example we have seen a lot of:
1 New Arraylist<string> ();
We can also define our own generics with inheritance, and here is a generic interface that inherits the list interface:
1 Interface extends List<e> {2 void setpayload (int index, P val); 3 ... 4 }
If we have the following class to implement the interface:
1 payloadlist<string,string>2 payloadlist<string,integer>3 Payloadlist<string,exception>
Then the relationship between them is:
Summary: Generics with two classes (or even the same class) have inheritance (or implementation) relationships that do not represent the relationships between these two classes. Unless the two classes have explicit inheritance (or implementation relationships), the relationships between their generics do not affect them.
References:
Https://docs.oracle.com/javase/tutorial/java/generics/inheritance.html
Java Generic Learning Notes-(vi) Inheritance of generics