To understand the co-organizer and the inversion in Java, we have to start from the inheritance, if there is no inheritance, covariance and inversion also naturally does not exist .
We know that there is an inheritance mechanism in the Java world. For example, the Mochacoffee class is a derived class of the coffee class, then we can use the Mochacoffee class reference at any time to replace the reference to the coffee class (When overriding the function, the parameter must be exactly the same as the overriding function, which is a column outside). Without throwing a compile error (as to whether the program function error will be raised depends on the code's compliance with the Richter replacement principle).
In short, if Class B is a derived class of Class A, a reference to Class B can be assigned to a reference to Class A .
There are two most common ways to assign values.
First: Use the equals operator to assign values explicitly
New Mochacoffee ();
The code above can be understood in two stages, first, new Mochacoffee () returns a reference to Mochacoffee, and then explicitly assigns this reference to a reference of type coffee.
Second: function parameter assignment
Public class Main { publicstaticvoid main (string[] args) { function ( New Mochacoffee ()); } Public Static void function (Coffee Coffee) { }}
After reviewing the basic knowledge, we formally begin to enter the world of covariance and inversion, first of all we look at the following common code:
New Mochacoffee[10]; Listextendsnew arraylist<mochacoffee>(); ListSupernew arraylist<coffee> ();
Each line of these three lines of code looks as if it can barely be understood, but the three lines of code seem to reveal some confusion about the inner order:
Mochacoffee[] is a subclass of coffee[]?
Arraylist<mochacoffee> is list< Extends Coffee> 's subclass?
Arraylist<coffee> is list< The subclass of Super mochacoffee>?
We've only learned that there is an inheritance relationship between classes, and that there is an inheritance relationship between these arrays and container types, which is defined in which source code is the JDK? Is there any other similar situation?
If you have a similar problem, it means that there is a lack of knowledge in your knowledge system, which is what we are talking about today in Java, covariance and contravariance.
What is the covariance? What is the inverse change?
Definition: Suppose f (x) represents a code pattern in Java, where x is a variable part of this pattern. If B is a derived class and F (b) also enjoys the treatment of a derived class F (a), then the F pattern is covariant, and if f (a) in turn enjoys the benefits of the F (b) derived class, then the F pattern is contravariant. If there is no inheritance between f (A) and F (B), then the F pattern is unchanged. (The inherited treatment here refers to the " if Class B is a derived class of Class A, then a reference to Class B can be assigned to a reference to Class A .") ”)
Most of the code patterns in Java are immutable (you can be reassured).
Java is currently known to support covariant and contravariant mode, I summed up three categories, welcome to Add.
First: f (x) = array of x, at which time F mode is covariant
New Coffee[10new mochacoffee[10//B can be assigned to a
This can answer the previous question, although mochacoffee[] is not a subclass of coffee[], but the array of this code pattern is covariant, so mochacoffee[] can also be directly assigned to coffee[].
It is important to note that although arrays are covariant, arrays are remembered for actual types and are type checked every time an element is added to an array. For example, the following code can be compiled by using the covariance of the array, but the runtime still throws an exception.
New mochacoffee[10];a[new// throws Arraystoreexception
This is why the covariance design of arrays is widely criticized, because exceptions should be found at compile time rather than deferred to runtime. However, after the array supports covariance, java.util.arrays#equals (java.lang.object[], java.lang.object[]) This type of function does not need to be implemented separately for each possible array type. The covariance design of arrays has historical compatibility considerations, and every design in Java may not be optimal, but it is the best choice that designers can make at the time.
Second: F (x) = x is passed <? Extend x> syntax as a generic parameter, when F mode is covariant
extends New Arraylist<mochacoffee>(); Listextendsnew arraylist<mochacoffee>//B can be assigned to a
The same, although arraylist<mochacoffee> is not list< Extends coffee> subclass, but list<? Extends x> This code pattern is covariant, so B can be assigned directly to a.
It is worth noting that, although the use of covariance, arraylist<mochacoffee> can be assigned to LIST< Extends Coffee>, but after assignment, list< Mochacoffee cannot be removed in extends coffee>, and only null can be added. Because the List is not the same as the array, he will not store the actual type of the elements, only rely on the declaration to do strict type checking, list< The extends Coffee> declaration means that the element type in this container is not deterministic and may be any subclass of Coffee, so it is unsafe to add any type to it, but you can remove the Coffee type. As follows:
extends New Arraylist<mochacoffee>(); // // Cannot add Mochacoffee/ /// Cannot add coffeea.add ( Null// can add null// can be removed coffee
Third: F (x) = x is passed <? Super x> syntax as a generic parameter, when F-mode is contravariant
Super New Arraylist<coffee>(); ListSupernew arraylist<coffee>//B can be assigned to a
Arraylist<coffee> not list<? Super mochacoffee> subclasses, but list<? Super X> This code pattern is contravariant, so B can be assigned directly to a.
It is worth noting that, although using inverse degeneration, arraylist<coffee> can be assigned to LIST< Super Mochacoffee>, but after assignment, list< You cannot add coffee in super mochacoffee>, and you can only remove object (unless you are forcing type conversions). list<? The super Mochacoffee> declaration means that the element type in this container is not deterministic and may be any base class for Mochacoffee, so adding mochacoffee and its subclasses to it is safe, but the type taken out can only be the topmost base class object. As follows:
Super New Arraylist<coffee>(); // // Cannot add coffeea.add (new// can add Mochacoffee// Only object can be removed
Note: Generic patterns without extend and super keywords are invariant, there is an inheritance relationship between A and B, but there is no inheritance between list<a> and list<b>, which resolves the problem caused by the array covariance mentioned above. Making type errors can be found at compile time.
Complementary knowledge Points:
The 2nd and 3rd notes also embody the famous pecs principle: "Producer extends,consumer Super".
If the generic parameter represents a being producer, use <? Extends T>. Because I want to be a producer of this parameter type, I need to tell someone that you want to use the T type to receive what I have produced for you.
If the generic parameter represents a consumer, use <? Super t>. Because I want to be a consumer of this parameter type, I need to tell someone that you give me something to consume and I'm going to use this type of T to receive it.
For example, Java8 new function interface Java.util.function.consumer#andthen method embodies the principle of Consumer super.
Summarize:
1, the array is covariant.
2. The generic type of extend keyword is covariant.
3, super keyword plus the generic type is contravariant.
4. Note the type restrictions for adding and getting elements in arrays and generic containers.
Java Advanced Knowledge Point 2: Code not understood-covariance and contravariance