In this example you will learn how to create a generic class in Java. In some 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.generics;
public class GenericMachine<T> {
private final T engine;
public GenericMachine(T engine) {
this.engine = 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();
}
private void start() {
System.out.println("This machine running on: " + engine);
}
}
Now, for the two engine class we will only create an empty class so that the GenericMachine
class can be compiled successfully. And here are the engine classes:
package org.kodejava.generics;
public class DieselEngine {
}
package org.kodejava.generics;
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.
- How do I use Proxy class to configure HTTP and SOCKS proxies in Java? - March 27, 2025
- How do I retrieve network interface information using NetworkInterface in Java? - March 26, 2025
- How do I work with InetAddress to resolve IP addresses in Java? - March 25, 2025