Recipe 3.9 Creating Getter/Setter Methods 3.9.1 Problem You need to create getter/setter methods for a field (for example, when creating properties in a JavaBean ), and you are looking for a shortcut. 3.9.2 Solution Select Source Generate Getter and Setter. 3.9.3 Discussion Say your code uses a field named text to store the text it displays: public class DisplayApp { static String text = "No problem."; public static void main(String[] args) { System.out.println(text); } } Instead of storing that data in a simple field, you can create getter and setter methods for that data, making access to the data from outside the class more secure. To automatically create getter and setter methods, select Source Generate Getter and Setter, opening the dialog shown in Figure 3-12. Select the field for which you want a getter and setter, as well as the methods to create, and click OK. Figure 3-12. Creating getter/setter methods This creates the new getter and setter methods shown here: public class DisplayApp { static String text = "No problem."; public static void main(String[] args) { System.out.println(getText( )); } /** * @return */ public static String getText( ) { return text; } /** * @param string */ public static void setText(String string) { text = string; } } |