Make Selenium Easy

#2. Creating Generic Class With Multiple Type Parameters

Introduction

Generics were introduced in Java 1.5 with the purpose of identifying probable run time errors related to type at compile time itself. It provides stronger type checks at compile-time and makes a class, interface and methods type-safe. It also eliminates explicit type casting.

In the last post, we already learnt about Generics and Generic class in Java. In this post, we will learn –

  1. How to create a generic class with multiple type parameters?
  2. How to use both type parameters and concrete types in a Generic class?
  3. What is raw type of generic class?

Creating generic class with multiple parameters

We can use multiple type parameters in a generic class. Java convension says to single uppercase letter as type parameter. The most commonly used type parameter names are:

  • E – Element (used extensively by the Java Collections Framework)
  • K – Key
  • N – Number
  • T – Type
  • V – Value
  • S,U,V etc. – 2nd, 3rd, 4th types

Below class is an example of generic class with multiple type parameters and explicit parameters.

We can use above class as below –

Raw Type of generic class

If we instantiate a generic class without passing type arguments then the compiler will give you a warning stating that the generic class is a raw type. It will not give any error and stop you from using this class but again we will be stuck in the problems discussed in this post.

Type Parameters vs Type Arguments

When we create a generic class then we pass a type parameter but when we instantiate that generic class then we pass type arguments.

That’s all in this post. We are going to learn a lot about generics in upcoming posts.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe to my YouTube channel.
#ThanksForReading
#HappyLearning

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.