Constructor overloading in Java – best practice

While there are no “official guidelines” I follow the principle of KISS and DRY. Make the overloaded constructors as simple as possible, and the simplest way is that they only call this(…). That way you only need to check and handle the parameters once and only once. public class Simple { public Simple() { this(null); … Read more

Why can’t I overload constructors in PHP?

You can’t overload ANY method in PHP. If you want to be able to instantiate a PHP object while passing several different combinations of parameters, use the factory pattern with a private constructor. For example: public MyClass { private function __construct() { … } public static function makeNewWithParameterA($paramA) { $obj = new MyClass(); // other … Read more

Why is a public const method not called when the non-const one is private?

When you call a.foo();, the compiler goes through overload resolution to find the best function to use. When it builds the overload set it finds void foo() const and void foo() Now, since a is not const, the non-const version is the best match, so the compiler picks void foo(). Then the access restrictions are … Read more

method overloading vs optional parameter in C# 4.0 [duplicate]

One good use case for ‘Optional parameters’ in conjunction with ‘Named Parameters’ in C# 4.0 is that it presents us with an elegant alternative to method overloading where you overload method based on the number of parameters. For example say you want a method foo to be be called/used like so, foo(), foo(1), foo(1,2), foo(1,2, … Read more

Method overloading in Objective-C?

Correct, objective-C does not support method overloading, so you have to use different method names. Note, though, that the “method name” includes the method signature keywords (the parameter names that come before the “:”s), so the following are two different methods, even though they both begin “writeToFile”: -(void) writeToFile:(NSString *)path fromInt:(int)anInt; -(void) writeToFile:(NSString *)path fromString:(NSString … Read more

Why does String.valueOf(null) throw a NullPointerException?

The issue is that String.valueOf method is overloaded: String.valueOf(Object) String.valueOf(char[]) Java Specification Language mandates that in these kind of cases, the most specific overload is chosen: JLS 15.12.2.5 Choosing the Most Specific Method If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to … Read more