
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Variance in Java
Java, with its robust object-oriented programming features, offers a multitude of mechanisms for programmers to develop flexible and efficient code. One such concept, often overlooked but critically important, is variance. Understanding variance is crucial for mastering Java, especially when working with generics and collections. This article provides an in-depth exploration of variance in Java, covering its types - covariance, contravariance, and invariance - and their practical applications.
Understanding Variance
Variance refers to how subtyping between more complex types relates to subtyping between their components. In simpler terms, it determines how the type hierarchy of classes is preserved when these classes are used as type parameters. Variance becomes particularly relevant when dealing with generics, providing a framework to ensure type safety while allowing some degree of flexibility in assignments.
Variance can be divided into three main types:
Covariance ? If ClassB is a subclass of ClassA, then Collection
can be treated as a subclass of Collection . Contravariance ? If ClassB is a subclass of ClassA, then Collection
can be treated as a subclass of Collection . Invariance ? Collection
and Collection have no subtype relationship, regardless of the relationship between ClassA and ClassB.
Let's delve deeper into each of these concepts.
Covariance in Java
Covariance is achieved in Java through the use of the wildcard with an extends clause. Let's consider an example ?
List<Animal> animals = new ArrayList<>(); <List<super Cat>cats=animals;
In this scenario, you can add a Cat object or any of its instances to cats, but you cannot read from cats and treat the result as a Cat, because it might hold any super type of Cat, including Animal or Object. Therefore, you can write into cats, but you cannot read from it in a type-safe manner
Invariance in Java
Invariance is the default behavior in Java and means there is no subtype relationship between Collection