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!

The Linux Command Line

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

The Linux Command Line takes you from your very first terminal keystrokes to writing full programs in Bash, the most popular Linux shell. Along the way you'll learn the timeless skills handed down by generations of gray-bearded, mouse-shunning gurus: file navigation, environment configuration, command chaining, pattern matching with regular expressions, and more.

$ Check price
39.9539.95Amazon 4.5 logo(274+ reviews)

More Linux & UNIX resources

Learn Enterprise Java Development for a Bright Career

Core Java, Volume II

Learn Enterprise Java Development for a Bright Career Try Java

Designed for serious programmers, this reliable, unbiased, no-nonsense tutorial illuminates advanced Java language and library features with thoroughly tested code examples. As in previous editions, all code is easy to understand and displays modern best-practice solutions to the realworld challenges faced by professional developers.

$ Check price
59.9959.99Amazon 4 logo(34+ reviews)

More Java resources