Item 41: Use overloading judiciously

1.  The choice of which overloading to invoke is made at compile time. Selection among overloaded methods is static, while selection among overridden methods is dynamic.

 

2.  A safe, conservative policy is never to export two overloadings with the same number of parameters. If a method uses varargs, a conservative policy is not to overload it at all.

 

3.  ObjectOutputStream has a variant of its write method for every primitive type and for several reference types. Rather than overloading the write method, these variants have signatures like writeBoolean(boolean), writeInt(int), and writeLong(long). An added benefit of this naming pattern, when compared to overloading, is that it is possible to provide read methods with corresponding names.

 

4.  Multiple constructors for a class are always overloaded. You do, in many cases, have the option of exporting static factories instead of constructors.

 

5.  Exporting multiple overloadings with the same number of parameters is unlikely to confuse programmers if it is always clear which overloading will apply to any given set of actual parameters. This is the case when at least one corresponding formal parameter in each pair of overloadings has a “radically different” type in the two overloadings. Two types are radically different if it is clearly impossible to cast an instance of either type to the other. 

 

6.  Array types and classes other than Object are radically different. Also, array types and interfaces other than Serializable and Cloneable are radically different.

 

7.  You should at least avoid situations where the same set of parameters can be passed to different overloadings by the addition of casts.

 

8.  It causes no harm as long as both overloaded methods always do exactly the same thing when they are invoked on the same object reference. (i.e. String.contentEquals can take either StringBuffer and CharSequence as parameter.) The standard way to ensure this behavior is to have the more specific overloading forward to the more general.

 

你可能感兴趣的:(overriding,overloading)