Java Generic Class Examples

In this post, we will show you the Java generics class examples. We will learn the how to write Generic Stack class with example.

Java Generic Class Syntax

A generic class is defined with the following format:
class name<T1, T2, ..., Tn> { /* ... */ }
The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the type parameters (also called type variables) T1, T2, ..., and Tn.

Java Generic Class Examples

In this post, we will see two complete examples.

Create Generic GenericFactory to get any Type of Instance

/**
 * Generic class example. Create GenericFactory<T> to get any type of instance.
 * @author javaguides.net
 *
 */
public class GenericClassExample {
    public static void main(String[] args) throws IllegalAccessException, InstantiationException {
        GenericFactory<ProductA> factory = new GenericFactory<ProductA>(ProductA.class);
        ProductA productA = factory.createInstance();
        System.out.println(productA.getProductName());

        GenericFactory<ProductB> factoryB = new GenericFactory<ProductB>(ProductB.class);
        ProductB productB = factoryB.createInstance();
        System.out.println(productB.getProductName());
   
        GenericFactory<ProductC> factoryC = new GenericFactory<ProductC>(ProductC.class);
        ProductC productC = factoryC.createInstance();
        System.out.println(productC.getProductName());
    }
}

class ProductA {
    public String getProductName() {
         return "Product A";
    }
}

class ProductB {
    public String getProductName() {
         return "Product B";
    }
}

class ProductC {
    public String getProductName() {
         return "Product C";
    }
}

class GenericFactory<T> {

    Class theClass = null;

    public GenericFactory(Class theClass) {
         this.theClass = theClass;
    }

    public T createInstance() throws IllegalAccessException, InstantiationException {
        return (T) this.theClass.newInstance();
    }
}
Output:
Product A
Product B
Product C

Generic Stack Example

  1. Create a generic Stack class.
class Stack<E> {
    private final int size;

    private int top;

    private E[] elements;

    public Stack() {
         this(10);
    }

    @SuppressWarnings("unchecked")
    public Stack(int s) {
        size = s > 0 ? s : 10;
        top = -1;
        elements = (E[]) new Object[size]; // create array
    }

    public void push(E pushValue) {
         if (top == size - 1) // if stack is full
            throw new FullStackException(String.format("Stack is full, cannot push %s", pushValue));

         elements[++top] = pushValue; // place pushValue on Stack
    }

    public E pop() {
         if (top == -1) // if stack is empty
            throw new EmptyStackException("Stack is empty, cannot pop");

        return elements[top--]; // remove and return top element of Stack
    }
}
  1. Create a custom exception to check full and empty of Stack - EmptyStackException, FullStackException.
class EmptyStackException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public EmptyStackException() {
         this("Stack is empty");
    }

    public EmptyStackException(String exception) {
         super(exception);
    }
}

class FullStackException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    public FullStackException() {
         this("Stack is full");
    }

    public FullStackException(String exception) {
         super(exception);
    }
}
  1. Let's create a Main class to a demonstrates a generic class example.
/**
 * Create Generic Stack. 
 * @author javaguides.net
 *
 * @param <E>
 */

public class GenericStackExample {

    private static Double[] doubleElements = { 1.1, 2.2, 3.3, 4.4, 5.5};

    private static Integer[] integerElements = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    private static Stack<Double> doubleStack = new Stack<Double>(5); // Stack of
                  // Doubles

    private static Stack<Integer> integerStack = new Stack<Integer>(10); // Stack
                   // of
                   // Integers
    // generic method testPush pushes elements onto a Stack

    private static <T> void testPush(String name, Stack<T> stack, T[] elements) {
         try {
               System.out.printf("\nPushing elements onto %s\n", name);

               for (T element : elements) {
                    System.out.printf("%s ", element);
                    stack.push(element);
               }
          } catch (FullStackException fullStackException) {
               System.out.println();
               fullStackException.printStackTrace();
          }
     }

    // generic method testPop pops elements from a Stack
    private static <T> void testPop(String name, Stack<T> stack) {
        try {
           System.out.printf("\nPopping elements from %s\n", name);
           T popValue;
           while (true) {
                popValue = stack.pop();
                System.out.printf("%s ", popValue);
           }
        } catch (EmptyStackException emptyStackException) {
               System.out.println();
               emptyStackException.printStackTrace();
        }
    }

    public static void main(String args[]) {
         testPush("doubleStack", doubleStack, doubleElements);
         testPop("doubleStack", doubleStack);
         testPush("integerStack", integerStack, integerElements);
         testPop("integerStack", integerStack);
    }
}
Output:
Pushing elements onto doubleStack
1.1 2.2 3.3 4.4 5.5 
Popping elements from doubleStack
5.5 4.4 3.3 2.2 1.1 
com.javaguides.generics.classes.EmptyStackException: Stack is empty, cannot pop

Pushing elements onto integerStack
1 2 3 4 5 6 7 8 9 10 
Popping elements from integerStack
10 9 8 7 6 5 4 3 2 1 
com.javaguides.generics.classes.EmptyStackException: Stack is empty, cannot pop

Related Java Generics Examples

Comments