Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: wordsmithing

...

Noncompliant Code Example (Constructor)

Constructors cannot be overridden and  and can only be overloaded. This noncompliant code example shows the constructor class Con with three overloadings: Con(int, String), Con(String, int), and Con(Integer, String)overloaded constructors.

Code Block
bgColor#FFCCCC
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 overloadings constructors contain the same number of similarly typed actual parameters. Overloading must also be avoided when the overloaded constructors or methods provide inconsistent functionality distinct semantics for formal parameters of the same types, differing solely in their declaration order.

...

Code Block
bgColor#ccccff
public static Con conName1createCon1(int i, String s) { /* Initialization Sequence #1 */ }
public static Con conName2createCon2(String s, int i) { /* Initialization Sequence #2 */ }
public static Con conName3createCon3(Integer i, String s) { /* Initialization Sequence #3 */ }

...

In this noncompliant code example, the BadOverloading class holds a HashMap instance and has overloaded getData() methods. One getData() method chooses the record to return on the basis of either its key value in the map; the other on the basis of the actual mapped value. For purposes of overload resolution, the signatures of the getData() methods differ only in the static type of their formal parameters. The BadOverloading class inherits from java.util.HashMap and overrides its get() method to provide the checking functionality. This implementation can be extremely confusing to the client who expects the both getData() methods to behave in a similar fashion and not depend on whether an index of the record or the value to be retrieved is specified.

...