Java — Generic Types

Ben Parker
1 min readJan 7, 2021

--

Overview

Generic Types in Java are a way to define methods and classes which can handle any type of object you want to pass. These are mostly used in APIs so they are more flexible.

Generic Methods

In order to define a generic method, you need:

  • Type Parameter — This is a diamond operator before the return type of the method, in the declaration. This tells the compiler that this method will be dealing with generic types. These type parameters can be bounded. Bounded type parameters are generic parameter which are more restricted in the objects that can be accepted. An unbounded type parameter would be expressed as

<T>

Where as a bounded type parameter could be

<T extends Collection>

This limits the acceptable object types to be any that extend the Collection interface.

There can also be multiple type parameters defined in a single method. In this case, the method would list the type parameters, separated by commas in the method signature.
For example:

public static <T, K> void testMethod(T param1, K param2)

This just means that method is dealing with multiple generic types. Each one of these parameters can be bounded.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Ben Parker
Ben Parker

No responses yet

Write a response