Yeah, @raimavaswani’s approach is pretty solid. I’ve also been in situations where a java generic interface was helpful, but sometimes I needed more flexibility on the fly. That’s where a generic method really shines.
public static <T> T getInput(Scanner sc, Class<T> type) {
return type == Integer.class ? type.cast(sc.nextInt()) : type.cast(sc.nextLine());
}
This allows you to dynamically choose the input type at runtime, without tying it to a specific implementation of the interface. It complements the java generic interface approach, especially in more dynamic use cases.