Recipe 3.5 Creating a Java Method

     

3.5.1 Problem

You want to create a Java method to run your code.

3.5.2 Solution

Enter the method's code yourself in the JDT editor, or let code assist help out.

3.5.3 Discussion

Java code must be in a method to be run. Eclipse, with code assist, can help out. Say you want to create the code you see in Example 3-1, which includes a new method named display .

Example 3-1. The DisplayApp.java example
 public class DisplayApp {     public static void main(String[] args)     {         display( );     }  private static void display( )   {   System.out.println("No problem.");   }  } 

To see what code assist can do for you, create the DisplayApp project, and let Eclipse generate a main method for you:

 public class DisplayApp {     public static void main(String[] args) {     } } 

Instead of typing in the display method by hand, use code assist. Move the cursor beneath the main method, and enter the word private to make display a private method. Then, press Ctrl-Space to open code assist, as shown in Figure 3-8.

Figure 3-8. Creating a new method
figs/ecb_0308.gif

Select the private static method item, and code assist will create the method template for you, as shown in Figure 3-9.

Figure 3-9. A new method template
figs/ecb_0309.gif

Fill in the return_type , name , and arguments items to give you the code in Example 3-1; save the file; and run the project by selecting Run Run As Java Application. You should see " No problem. " in the Console view.

Eclipse also can create methods for you automatically if your code calls them. To see how that works, delete or comment out the display method in your code. Click the Quick Fix light bulb that appears next to the call to display in the main method, and select Create method ' display(...) '. Using the signature of the method you're calling, Eclipse will create a method skeleton for you.




Eclipse Cookbook
Inside XML (Inside (New Riders))
ISBN: 596007108
EAN: 2147483647
Year: 2006
Pages: 232
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net