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.

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

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

Ad