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'm currently creating a class to handle menu options. So far I am able to create menu's with options ie:
And I have written the code in order to output the options so it looks like this:
So here is where I don't know if there is better method to implement what I want to do next, but essentially right now I take the user input and then I use a switch and case in a HandleMenu file. I don't think this is the best solution because it implies that I have knowledge of all the menu options.
I want to somehow include the method call in the Menu class so it would look something like this:
Does anyone have an idea on how I would implement this; I hope I was clear.
You could encapsulate the function call in an interface. For example:
(That's using an anonymous inner class - there are other ways if you don't like them).
Then in the Menu class, store the MenuCall objects against the option numbers. When the option is entered, extract the MenuCall and call execute() on it. Your Menu class doesn't have to know anything about what the options are. That would do what it sounds you're looking for.
You cannot pass a method as an argument. Methods aren't first-class objects in Java™. What you would get is the return type from that method passed.
I presume you are running this from the command line; it is completely different if you use Swing.
I can think of several non-GUI ways to implement a menu. In addition to the use of an enum, you can enter the numbers and use a switch block. You can put the Strings and objects which will carry out the actions into a Map, and use the Strings as keys to retrieve the action objects.