Java Reference
In-Depth Information
class Con {
public Con(int i, String s) {
// Initialization Sequence #1
}
public Con(String s, int i) {
// Initialization Sequence #2
}
public Con(Integer i, String s) {
// Initialization Sequence #3
}
}
Failure to exercise caution while passing arguments to these constructors can create
confusion because calls to these constructors contain the same number of similarly typed
actual parameters. Overloading must also be avoided when the overloaded constructors
or methods provide distinct semantics for formal parameters of the same types, differing
solely in their declaration order.
Compliant Solution (Constructor)
Thiscompliantsolutionavoidsoverloadingbydeclaringpublicstaticfactorymethodsthat
have distinct names in place of the public class constructors:
Click here to view code image
public static Con createCon1(int i, String s) {
/* Initialization Sequence #1 */
}
public static Con createCon2(String s, int i) {
/* Initialization Sequence #2 */
}
public static Con createCon3(Integer i, String s) {
/* Initialization Sequence #3 */
}
Noncompliant Code Example (Method)
In this noncompliant code example, the OverLoader class holds a HashMap instance and
has overloaded getData() methods. One getData() method chooses the record to re-
turn on the basis of its key value in the map; the other chooses on the basis of the actual
mapped value.
Search WWH ::




Custom Search