Created
August 1, 2020 13:11
-
-
Save nitinbhojwani/656211120ed6b7d2644e0062ddb983e3 to your computer and use it in GitHub Desktop.
Generics(Function and Class) in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// IntegerProcessor - implements Processor for Integer type - processes Integer objects | |
public class IntegerProcessor implements Processor<Integer> { | |
public void process(Integer obj) { | |
// process Integer object here | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Processor interface - that processes object of type T | |
public interface Processor<T> { | |
void process(T obj); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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