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!

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

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