Notes on learning Java covariant and Inverter

Source: Internet
Author: User

In object-oriented computer programming languages, conversions between types are often involved, for example, type conversion from a specific kitten to an animal (upstream conversion ), or convert from shape to Triangle (downstream conversion ).
We often focus on the Type itself before, but often ignore the nature of type conversion. I recently read thinking in Java and read some abstract theories about the nature of type conversion. I will take a closer look and share them with you.
We will focus on three core terms: covariance, contravariance, and invariant ). They are all terms used to describe the nature of type conversion. The formal descriptions are as follows:

If A and B are types, f Represents type conversion, and ≤represents the child type relationship (for example, a ≤ B, indicating a is a subclass of B), then:
If a is less than or equal to B, F (a) is less than or equal to F (B). Then f is a covariant.
If a is less than or equal to B, F (B) is less than or equal to f (a), F is an inverter.

If neither of the above is true, F is irrelevant.

For example, in Java, f (a) = List <A>. The list declaration is as follows:
Class list <t> {...}
We can understand that a generic list type input a type parameter T and converts t to a type list <t>. This process is a type conversion process.
For example, a = object, B = string, f (a) = List <Object>, F (B) = List <string> after type transformation.
String ≤ object, but f (a) ≤ F (B) is not true.
Therefore, the above type conversion is irrelevant.

In Java, there are some syntaxes that can be understood using Covariance and inversion.
Array
For example, a = string, B = object. Here we have a ≤ B.
F (a) = string [], F (B) = object []. Because object [] objects = new string [N]. Therefore, we can think that the array has a covariance.

X = y

1. covariant Return Value

In object-oriented language, a covariant return value method is a method that can be replaced by a "narrower" type when the subclass overwrites the method.
(C # does not support this technology. c ++ and Java jdk5.0 will be supported later)
For example:

public static class Super {      Object getSomething() {      return null;   }}
public static class SubClass extends Super {@Override     String getSomething() {           return null;     }}

The main idea of this section is that the collaborative return value is used when the subclass requires a return value different from that of the parent override method, but the return value has an inheritance relationship.
A better example is as follows:

class Collection {     Iterator iterator() { ... }}class List extends Collection {    @Override     ListIterator iterator() { ... }} 

The iterator function obtains the iterator of the current set. In the subclass, The iterator has a more precise representation, so the listiterator subclass of iterator is used as the new return value.

2. inverter Parameters

For example, you can understand the example of inverter parameters at once. In fact, the environment of inverter parameters is still covered by functions in the inheritance system.

class Super {          void doSomething(String parameter) {          }}class Sub extends Super {        void doSomething(Object parameter) {         }}

To better understand this problem, first introduce the concept of liskov substitution principle. This principle means that the subclass object can be used wherever the parent class object is needed.
What is the relationship between this principle and parameters and returned values?
Suppose we define the class as follows:

class Super {       ReturnType doSomething(ParameterType a) {            return null;       }}class Sub extends Super {       ReturnType doSomething(ParameterType a) {                return null;       }}

Suppose I have super sup;
First, consider the parameter. Now we need to call sup. dosomething (O );
If the parameter types required by the two functions are the same, there is nothing worth discussing. In some cases, the parameter type required by sub is changed to newparametertype, which has an inheritance relationship with parametertype. As follows:

class Sub extends Super {          ReturnType doSomething(NewParameterType a) {                return null;          }}

If newparametertype is a subclass of parametertype, In the sup. dosomething (o) call, if o is an object pointing to newparametertype, it will not pass. No problem occurs only when newparametertype is the parent class of parametertype. Therefore, the concept of inverter parameters is proposed.
Similarly, this principle can be used for understanding.
Assume that the following statements are available in a certain environment:
Returntype RT = sup. dosomething (O );
If the design change occurs, the subclass must return a newreturntype class that has an inheritance relationship with the returntype. If the returned class is a returntype parent class, the above statement cannot be compiled, only when newreturntype is a subclass of returntype will it not violate the liskov subclass principle.

Java generic
In Java generics, for example
Class dataholder <t> {

}
If the type A is less than or equal to B, but directly using dataholder <A> and dataholder <B> is immutable, we have already described it.
However, using the wildcard syntax provided by Java, you can provide a type conversion for a covariant.
Dataholder <A> ≤ dataholder <? Extends B>

For example:

static boolean find(Iterable<? extends Object> where, Object what){        return false;}

You can use iterable <string> to call the find function.

References:

Http://stackoverflow.com/questions/2501023/demonstrate-covariance-and-contravariance-in-java

Http://en.wikipedia.org/wiki/Covariance_and_contravariance_ (computer_science)

Http://www.cnblogs.com/pugang/archive/2011/11/09/2242380.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.