02. Generic Classes

Let's jump right into an example of a generic class.

public class Container<E> {
 
  private E element;
 
  Container() { element = null; }
  Container(E element) { this.element = element; }  
 
  public void set(E element) { this.element = element; }
  public E get() { return this.element; }
 
}

The class above is a Container, which stores an element E of any type the user specifies.

Formal and Actual type parameters

The letter in the brackets <E> is known as the formal type parameters.

This descibes some element type. When we instantiate the Container object and define a type, the E is replaced by the actual type argument.

Let's see how instantiation is done below.

Instantiation

To invoke this class, we perform a generic type invocation.

Container<Integer> intContainer = new Container<>();

Note that we just have <> instead of <Integer> in our constructor. Since Java SE 7, the inclusion of the type in the second <> became optional.

Great! Now we have a container that can hold an integer.

An important caveat of using generics is that they don't accept primitive data types. Let's learn how Java Autoboxing handles this in our next lesson.

Take your Linux skills to the next level!

Linux for Beginners

Take your Linux skills to the next level! Try Linux & UNIX

Linux for Beginners doesn't make any assumptions about your background or knowledge of Linux. You need no prior knowledge to benefit from this book. You will be guided step by step using a logical and systematic approach. As new concepts, commands, or jargon are encountered they are explained in plain language, making it easy for anyone to understand.

$ Check price
24.9924.99Amazon 4.5 logo(101+ reviews)

More Linux & UNIX resources

Learn Enterprise Java Development for a Bright Career

Java, A Beginner's Guide

Learn Enterprise Java Development for a Bright Career Try Java

A book that is simple, direct, terse with easy examples. Simple example programs to guide you as you go, with test exercises at the end for you to judge for yourself how well you understand the program. Learn java faster and efficiently with Java: A Beginner's Guide.

$ Check price
4040Amazon 4.5 logo(245+ reviews)

More Java resources

Ad