Java – Generics

A generic class/method is the class/method that declares one or more type variables. With generic classes/method we skip the creation of multiple classes/method because of different type variables

Generic Method Example

Java generics bounded type parameters and diamond, <span>Java – Generics</span>, KandZ
Java generics bounded type parameters and diamond, <span>Java – Generics</span>, KandZ
Java generics bounded type parameters and diamond, <span>Java – Generics</span>, KandZ

One generic method instead overloading a method like this below:

Java generics bounded type parameters and diamond, <span>Java – Generics</span>, KandZ

Generic Class Example:

Java generics bounded type parameters and diamond, <span>Java – Generics</span>, KandZ
Java generics bounded type parameters and diamond, <span>Java – Generics</span>, KandZ
Java generics bounded type parameters and diamond, <span>Java – Generics</span>, KandZ

Restrictions:

  • You cannot instantiate primitives, you should use their wrapper class. ex: use Integer instead of int
  • You cannot declare static fields whose types are type parameters
  • You cannot create new instances of type parameters.

Diamond parameter <>:

You can just use an empty pair of angle brackets <> for one or more type parameters that a sufficiently-close context implies. For example:

Java generics bounded type parameters and diamond, <span>Java – Generics</span>, KandZ

it can be:

Java generics bounded type parameters and diamond, <span>Java – Generics</span>, KandZ

Bounded type parameters

You can restrict the kind of type that allowed to be passed to a type parameter. You can do this by using extends

Java generics bounded type parameters and diamond, <span>Java – Generics</span>, KandZ

If you need multiple bounds then you can combine them with &

Java generics bounded type parameters and diamond, <span>Java – Generics</span>, KandZ

THE END!!!

88580cookie-checkJava – GenericsJava – Generics

Related posts

One Thought to “Java – Generics

Comments are closed.