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 get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024