How to Use Generics with Abstract Classes in Java For Different Parameter Types

Published Aug 25, 2021

How can we support multiple parameter or return types in an abstract Java class?

Suppose we have two jobs, StringJob and DoubleJob, that share the same function that operates on different types.

public class StringJob {
    public String run(String a, String b) {
        // Do something
    }
}
public class DoubleJob {
    public double run(double a, double b) {
        // Do something
    }
}

We want to ensure this run() method is declared in both classes, but we can’t simply create an abstract class with either method definition because the types are different.

Luckily, we can use Java Generics.

We can first declare an abstract class that uses generics T.

public abstract class AbstractJob<T> {
    public abstract T run(T a, T b);
}

Our generic T could refer to any class (i.e. String, Double, Integer, etc.). This is declared when the AbstractJob class is referenced.

These generics can be named anything; it doesn’t have to be T.

We can then create child classes that extend this abstract class, each declaring their own type for the generic.

public class StringJob extends AbstractJob<String> {
    @Override
    public String run(String a, String b) {
        // Do something
    }
}
public class DoubleJob extends AbstractJob<Double>{
    @Override
    public Double run(Double a, Double b) {
        // Do something
    }
}

More Java Articles