Skip to content

Instantly share code, notes, and snippets.

@nitinbhojwani
Created August 1, 2020 13:11
Show Gist options
  • Save nitinbhojwani/656211120ed6b7d2644e0062ddb983e3 to your computer and use it in GitHub Desktop.
Save nitinbhojwani/656211120ed6b7d2644e0062ddb983e3 to your computer and use it in GitHub Desktop.
Generics(Function and Class) in Java
/**
* Generic Function example
* GenericProcessor has a generic function that takes two generic arguments of type T
* One of them is the object of type T
* Another one is the object that processes objects of type T
*/
public class GenericProcessor {
private <T> void processObjectGivenProcessor(
T object,
Processor<T> processor) {
processor.process(object)
}
}
// IntegerProcessor - implements Processor for Integer type - processes Integer objects
public class IntegerProcessor implements Processor<Integer> {
public void process(Integer obj) {
// process Integer object here
}
}
// Processor interface - that processes object of type T
public interface Processor<T> {
void process(T obj);
}
// StringProcessor - implements Processor for String type - processes String objects
public class StringProcessor implements Processor<String> {
public void process(String obj) {
// process String object here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment