| Author |
Dynamic Constructor Selection
|
Jim Ball
Greenhorn
Joined: Dec 05, 2006
Posts: 8
|
|
I am attempting to select the proper constructor based on args passed into the program because the args will determine which method gets run. Here is some code to clarify. The code below does work, but I want to eliminate the redundancy of the return = (some class).method(args). Is this a possibility? An example of what I want to do is written in pseudocode after the working code below. //Working code public static void main (String[] args){ int return = 1; if (args[0].equalsIgnoreCase("test1"){ return = (new Test1()).accept(args); } else if (args[1].equalsIgnoreCase("test2"){ return = (new Test2()).accept(args); } else return = (new Test3()).accept(args); System.exit(return); } //Pseudocode (code will not work just illustrating what I am hoping can be done.) public static void main (String[] args){ String testConstructor = ""; if (args[0].equalsIgnoreCase("test1"){ testConstructor = "(new Test1())"; } else if (args[1].equalsIgnoreCase("test2"){ testConstructor = "(new Test2())"; } else testConstructor = "(new Test3())"; int return = testConstructor + .accept(args); System.exit(return); }
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24051
|
|
Hi Jim, Welcome to JavaRanch... and welcome to Object-Oriented design 101. What you're looking for is called polymorphism, and it's truly the fundamental concept of object-orientation. You'll use it a lot in Java! The trick is that Test1, Test2, and Test3 need to all have some common type -- a superclass or an interface they all implement -- and that common type needs to define the "accept" method. Given that, then you can do If you need more help, like an idea of what Test1 and friends need to look like, then by all means ask me.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Jim Ball
Greenhorn
Joined: Dec 05, 2006
Posts: 8
|
|
|
Thanks for the help. I do understand what you are saying, and I will try it out.
|
 |
Jim Ball
Greenhorn
Joined: Dec 05, 2006
Posts: 8
|
|
Solution works, thanks again.
|
 |
 |
|
|
subject: Dynamic Constructor Selection
|
|
|