SE450: Java: Overloading [5/41] ![]() ![]() ![]() |
Overloading:Overloading refers to the ability to allow different methods or constructors of a class to share the same name. The name is said to be overloaded with multiple implementations.
When can you overload?: Two methods or constructors in the same class can be overloaded, i.e., sharing the same name, if they have either different number of parameters or same number of parameters but of different types. In other words, no two methods or constructors in the same class may have identical signatures.
What does this program print? Why?
/* * CollectionClassifier.java * */ import java.util.*; /** * * @author From "Effective Java" by Joshua Bloch */ public class CollectionClassifier { /** Creates a new instance of CollectionClassifier */ public CollectionClassifier() { } public static String classify(Set s) { return "Set"; } public static String classify(List l) { return "List"; } public static String classify(Collection c) { return "Unknown Collection"; } /** * @param args the command line arguments */ public static void main(String[] args) { Collection[] tests = new Collection[] { new HashSet(), new ArrayList(), new HashMap().values() }; for(int i = 0; i < tests.length; i++) { System.out.println(classify(tests[i])); } } }
Note that Java allows overloading across subclasses, something that C++ doesn't allow. This can cause all sorts of confusion. The best rule is don't do it