flâneur — a map of the web's best reading

21. Variance - CS2030S Programming Methodology II

nus-cs2030s.github.io · 712 words · saved by 1 readers

Line 4 is not surprising since the type for objArray matches that of parameter array. Line 5, however, shows that it is possible to assign an instance with run-time type Integer[] to a variable with compile-time type Object[]. So far, we have established the subtype relationship between classes and interfaces based on inheritance and implementation. The subtype relationship between complex types such as arrays, however, is not so trivial. Let's look at some definitions. The variance of types refers to how the subtype relationship between complex types relates to the subtype relationship between components. Let 𝐶 ( 𝑆 ) corresponds to some complex type based on type 𝑆 . An array of type 𝑆 is an example of a complex type. We say a complex type is: Array is covariant in Java. This means that, if 𝑆 <: 𝑇 , then 𝑆 [ ] <: 𝑇 [ ] . For example, because Integer <: Object, we have Integer[] <: Object[] and we can do the following: By making array covariant, however, Java opens up th

Unit 21: Variance After this unit, students should: understand the definition of the variance of types: covariant, contravariant, and invariant. be aware that the Java array is covariant and how it could lead to run-time errors that cannot be caught during compile time. Both the methods findLargest and contains takes in an array of reference types as parameters: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 // version 0.4 GetAreable findLargest ( GetAreable [] array ) { double maxArea = 0 ; GetAreable maxObj = null ; for ( GetAreable curr : array ) { double area = curr . getArea

Explore this link on the map →

saved by

related reading