View Full Version : Set/Get Methods

02-15-2008, 04:22 PM
Hey all i am in need of some help figuring out how to use a set method in the problem below:

public class Test1 {
public static void main(String[] args) {
Sales s1 = new Sales("123","South",4500);

System.out.println(s1 + "\n");

and it calls Sales by this class:

public class Sales
private String id;
private String Region;
private double Amount;

public Sales(String theId, String theRegion, double theAmount)
id = theId;
Region = theRegion;
Amount = theAmount;

public String getID()
return id;

public String getRegion()
return Region;

public double getAmount()
return Amount;

public String toString()
return "ID: " + getID() + "\n" +
"Region: " + getRegion() + "\n" +
"Amount: " + getAmount() + "\n";

Now the code works but it only gets the values of "123","South",4500 and not the s1.setID("1123"). What do i need to add to the Sales class in order to read that setID?


02-15-2008, 05:13 PM
You need to add the method setID to your Sales class, just like you made your other methods.

First you set the access specifier. This can either be public, protected or private. Though get and set methods should generally be public.

Then you specify the return type. In the case of set methods, you should either make the methode return nothing, or make it return a boolean value to indicate whether the action succeeded or not. In this case the latter is not really necessary as not a lot can go wrong, so we go for the first option by using the keyword void as the return type. This indicates that the methode will return nothing at all.

Then the method name, which should be setID, as you described.

As for the parameters, you should have the value of the new ID that you want to use to overwrite the current ID with.

This information gives us the following method header:

public void setID(String newID)

The method now only needs a body where the current ID will be overwritten by the new ID. This can be done with just one single statement and gives us the following methode:

public void setID(String newId)
id = newId;

Also, I don't know if you're allowed to change the other methods, but I suggest making the id instance variable an int instead of a String object if IDs are numbers.

02-15-2008, 08:45 PM
Hey thanks Jero, your example worked just fine and now i understand it a little bit more :)

Thanks again,