Defining Generic Classes and Interfaces

Paul Ngugi - Jul 4 - - Dev Community

A generic type can be defined for a class or interface. A concrete type must be specified when using the class to create an object or using the class or interface to declare a reference variable. Let us revise the stack class in Case Study: A Custom Stack Class, to generalize the element type with a generic type. The new stack class, named GenericStack, is shown in Figure below and is implemented in the code below.

Image description

Image description

The following example creates a stack to hold strings and adds three strings to the stack:

GenericStack<String> stack1 = new GenericStack<>();
stack1.push("London");
stack1.push("Paris");
stack1.push("Berlin");

This example creates a stack to hold integers and adds three integers to the stack:

GenericStack<Integer> stack2 = new GenericStack<>();
stack2.push(1); // autoboxing 1 to new Integer(1)
stack2.push(2);
stack2.push(3);

Instead of using a generic type, you could simply make the type element Object, which can accommodate any object type. However, using generic types can improve software reliability and readability, because certain errors can be detected at compile time rather than at runtime. For example, because stack1 is declared GenericStack, only strings can be added to the stack. It would be a compile error if you attempted to add an integer to stack1.

To create a stack of strings, you use new GenericStack() or new GenericStack<>(). This could mislead you into thinking that the constructor of GenericStack should be defined as

public GenericStack<E>()

This is wrong. It should be defined as

public GenericStack()

Occasionally, a generic class may have more than one parameter. In this case, place the parameters together inside the brackets, separated by commas—for example,

<E1, E2, E3>

You can define a class or an interface as a subtype of a generic class or interface. For example, the java.lang.String class is defined to implement the Comparable interface in the Java API as follows:

public class String implements Comparable<String>

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player