How do I create a generic class in Java?

In this example you will learn how to create a generic class in Java. In some of the previous post in this blog you might have read how to use generic for working with Java collection API such as List, Set and Map. Now it is time to learn to create a simple generic class.

As an example in this post will create a class called GenericMachine and we can plug different type of engine into this machine that will be use by the machine to operate. For this demo we will create two engine type, a DieselEngine and a JetEngine. So let’s see how the classes are implemented in generic.

package org.kodejava.examples.generic;

public class GenericMachine<T> {
    private T engine;

    public GenericMachine(T engine) {
        this.engine = engine;
    }

    private void start() {
        System.out.println("This machine running on: " + engine);
    }

    public static void main(String[] args) {
        //
        // Creates a generic machine with diesel engine.
        //
        GenericMachine<DieselEngine> machine = new GenericMachine<>(new DieselEngine());
        machine.start();

        //
        // Creates another generic machine with jet engine.
        //
        GenericMachine<JetEngine> anotherMachine = new GenericMachine<>(new JetEngine());
        anotherMachine.start();
    }
}

Now, for the two engine class we will only create an empty class so that the GenericMachine class can be compile successfully. And here are the engine classes:

package org.kodejava.examples.generic;

public class DieselEngine {
}
package org.kodejava.examples.generic;

public class JetEngine {
}

The <T> in the class declaration tell that we want the GenericMachine class to have type parameter. We also use the T type parameter at the class constructor to pass the engine.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.