21. Variance - CS2030S Programming Methodology II
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
- 20. Casting - CS2030S Programming Methodology IInus-cs2030s.github.io
- 2. Variable and Type - CS2030S Programming Methodology IInus-cs2030s.github.io
- 14. Polymorphism - CS2030S Programming Methodology IInus-cs2030s.github.io
- 19. Wrapper Class - CS2030S Programming Methodology IInus-cs2030s.github.io
- 4. Encapsulation - CS2030S Programming Methodology IInus-cs2030s.github.io
- 17. Abstract Class - CS2030S Programming Methodology IInus-cs2030s.github.io
- Variance - Rust Compiler Development Guiderustc-dev-guide.rust-lang.org
- Generics: in, out, where | Kotlin Documentationkotlinlang.org
- artima - Josh Bloch on Designartima.com
- Immutable object - Wikipediaen.wikipedia.org
- Swift: From Protocol to AssociatedType then Type Erasure | Welcome to Monstarlab’s Engineering Blogengineering.monstar-lab.com
- Reading 12: Defining ADTs with Interfaces, Generics, Enums, and Functionsweb.mit.edu