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.


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!

Command Line Kung Fu

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

Command Line Kung Fu is packed with dozens of tips and practical real-world examples. You won't find theoretical examples in this book. The examples demonstrate how to solve actual problems. The tactics are easy to find, too. Each chapter covers a specific topic and groups related tips and examples together.

$ Check price
14.9914.99Amazon 4.5 logo(27+ reviews)

More Linux & UNIX resources

Learn Enterprise Java Development for a Bright Career

Head First Java

Learn Enterprise Java Development for a Bright Career Try Java

Jump start your Java education with Head First Java! This book provides clean diagram examples, with text that is easy-to-understand in an almost too-casual language. Great for anyone new to Java or programming in general.

$ Check price
44.9544.95Amazon 4.5 logo(567+ reviews)

More Java resources