This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I have a main program (public static void main( ... )). I have two classes. Both classes are doing the same thing but each uses its own method to do it. That is to say, class A uses Method A and class B uses Method B. Method A and Method B are different ways to do the same work.
How do I fetch those two different implementations in the main program using the same API calls?
Let me see if I got the question ... maybe your main looks like this:
and you'd like to eliminate the if test and different method calls? If that's the challenge, the interface suggestion is a good hint. Let us know if that's near the mark.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Nov 19, 2000
Thanks for being willing to help. I am applying for a job. In addition to phone interview, face-to-face interview, and other requirements, I have to write a Java program:
The random number generation service should allow at least two different implementations of the random number generator to be called from the same "main" program without code rewrites. The main program should be a Java program that fetches five random numbers from the random number generator service and displays them on the screen.
One of the random number generator is the Java built-in generator and I have to come up with the other random number generator (question is posted under another JavaRanch Forum topic and yet to be worked on).
I already have a scratch of the main program calling the Java built-in randome number generator:
I am trying to figure out how "the main program is able to fetch from either random number generator implementation using the same API calls", which is a requirement of this exercise.
Step 1: Give the "BuildInMethod" class a "getRandom()" method, and use it to fetch "x", instead of accessing the variable directly (to get more than one random number, you'll need to eliminate that member variable altogether, of course.) It's almost never good to write code that accesses the member variables of another class.
Step 2: Define an interface RandomNumberGenerator with a getRandom() method. Have "BuildInMethod" declare that it implements that method.
Step 3: Write another random number generator. Have it also implement that interface.
Now, as far as how main() should work: for this kind of program, I'd be partial to having the random number generator class's name on the command line, and using Class.forName().newInstance() to load it, and then cast it to RandomNumberGenerator before calling the getRandom() method.
Note that this loop:
for ( int i = 0; i <= 5; i++ )
will execute six times, not five. That "<=" should be a "<".