# Java getters and setters

Below is the code I would like some help with. I'm just trying to understand if there a better way to use getters and setters. Can someone fill me in on the correct way to use them if there is a textfield, JRadioButton set that I am trying to get info from?

//This class sets gets all the information that the user has entered.
package edu.witc.TrainTicket.model;

import java.text.NumberFormat;

import javax.swing.JOptionPane;
import javax.swing.JTextField;

import edu.witc.TrainTicket.view.*;

public class Destination {

//Constructor with no arguments
public Destination() {
}

String selectedDestination = getRadioButtonValue(chicago, newYork, seattle, sanFransisco);
String custName = getCustName(name);
String custPhone = getPhoneNum(phone);

}

public String getCustName(JTextField name){
return name.getText();
}

public String getPhoneNum(JTextField phone){
return phone.getText();
}

//get the type of paint

String selected = "";

if(chicago.isSelected())
selected = "Chicago";
if(newYork.isSelected())
selected = "New York";
if(seattle.isSelected())
selected=  "Seattle";
if(sanFransisco.isSelected())
selected=  "San Fransisco";

//JOptionPane.showMessageDialog(null, selected);

return selected;
}
}

• Just a note about useful comments: //Constructor with no arguments isn't one. //Parameterless constructor required for xyz is more informative. – Mathieu Guindon Oct 19 '13 at 0:59

Your getters and setters would be for fields of the class, not passed in. I'll use your two simplest ones as examples for you to work from.

public String getCustName(JTextField name){
return name.getText();
}

public String getPhoneNum(JTextField phone){
return phone.getText();
}


These methods make no sense if you think about them logically. Your client code will pass in a JTextField that it already has, in order to invoke getText() on it? Why wouldn't that code just do it itself?

Here's how getters and setters work:

private JTextField myTextField;

public String getMyTextFieldValue() {
return myTextField.getText();
}

public void setMyTextField(JTextField newTextField) {
myTextField = newTextField;
}


That's the general principle behind getters and setters. You should be able to extend that logic to all of the other methods as well once you understand the logic.

• Would I need a Constructor here – Justin Esders Oct 19 '13 at 4:05
• @JustinEsders Constructors are only needed if you either A) need/want default values in place or B) need to initialize other fields in your class. so in this simple case, he might need a constructor if myTextField is never initialized. – Robert Snyder Oct 19 '13 at 4:15