3.9. Creating Getter/Setter Methods
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.
Solution
Select Source→ Generate Getter and Setter.
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;
}
}Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access