January 5, 2010

Generic methods in Java


public static void main(String[] args) {
genericMethod("abc");
}

static void overloadedMethod(Object o) {
System.out.println("overloadedMethod(Object) called");
}

static void overloadedMethod(String s) {
System.out.println("overloadedMethod(String) called");
}

static void overloadedMethod(Integer i) {
System.out.println("overloadedMethod(Integer) called");
}

static <T> void genericMethod(T t) {
overloadedMethod(t);
}


produces output "overloadedMethod(Object) called"; this is because the generic method doesn't know what kind of argument will be passed in at compile time [DBL-CHECK REASON]

No comments:

Post a Comment