Generic Classes and Nullability

Learn how to work with generic classes and how to use type parameters.

Generic classes

We can make classes generic by adding a type parameter after the class name. Such a type parameter can be used all over the class body, especially to specify properties, parameters, and result types. A type parameter is specified when we define an instance, after which it remains unchanged. Thanks to that, when we declare ValueWithHistory<String> and then call setValue in the example below, we must use an object of type String; when we call currentValue, the result object will be typed as String; and when we call history, its result is of type List<String>. It’s the same for all other possible type arguments.

Get hands-on with 1200+ tech skills courses.