Showing posts with label overload. Show all posts
Showing posts with label overload. Show all posts

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]

December 24, 2009

Overriding vs. Overloading vs. Hiding

  • Overloading is using the same method name with a different parameter list.
  • Overriding is replacing a superclass method with a different and/or more specific one in a subclass.
  • Hiding is similar to overriding but not quite the same. In the special case where a subclass's static method has the same signature as a parent class's static method, the subclass's method hides rather than overrides the parent class's method. This makes the parent class's method completely unaccessible. TODO: Find out whether this is the only situation in which hiding applies.

Useful links
The best explanation I've found so far, from the JavaRanch FAQ

Also useful, from the Java Tutorials

This StackOverflow post is technically about .NET, but I think it's still correct for Java

Some examples from the Java Language Specification