This article explains how to create multiple constructors with the same arguments in the Java language. The same idea could also be applied in to code in the C++ language.
In Java you cannot have multiple methods (including constructors) with the same arguments. To get around this limitation you need to use static methods with different names which serve the client code as constructors. In the code that follows the static methods ctorApple, ctorBanana and ctorCarrot internally call the private constructor Foo() and serve in the role of multiple constructors with the same arguments. The prefix ctor is intended to remind the client that these methods serve in the role of constructors.
class Foo { private Foo() { // ... } public static Foo ctorApple(/* parameters */) { Foo f = new Foo(); // set properties here using parameters return f; } public static Foo ctorBanana(/* parameters */) { Foo f = new Foo(); // set properties here using parameters return f; } public static Foo ctorCarrot(/* parameters */) { Foo f = new Foo(); // set properties here using parameters return f; } }
Back to Research Projects |
This page has the following hit count:
|