Java‎ > ‎

Accessor Methods with Java Example

Below is a simple class that shows the difference between a SETTER method, and a GETTER method. an Accessor method is a GETTER method:
The Example below uses Java.


Something really cool that I have just found is that if you right click on your Java Code in Netbeans (I'm using Netbeans 6.5) you can generate getter and setter methods with only mouse clicks. The menu item you are looking for is "Insert Code" (or Alt+Insert)


class cup {

private String status = "The Cup Exists";
private boolean working = true;

   public void fill()
    {
    // Fill the cup (setter method)
        if(working) status = "The Cup has been filled";
    }

    public void empty()
    {
    // Empty the cup (setter method)
        if (working) status = "The Cup is Empty";
    }

   public void smash()
   {
     // smash the cup (setter method)
        working = false;
        status = "The Cup is broken";
   }

   public String getStatus()
   {
       // Return the current status of the cup
       // Accessor Method (getter method)
    return status;
   }

}

Additional Information about Getter and Setter methods can be found at Wikipedia:
http://en.wikipedia.org/wiki/Method_(computer_science)#Kinds_of_methods
http://en.wikipedia.org/wiki/Mutator_method
Comments