title: Accessor Methods in Java
body: <p>So I have a question on "setter" and "getter" methods and how useful they are or aren't.</p>
  
  <p>Let's say I just write a very basic program like the following:</p>
  
  <pre><code>    public class Account
      {
       String name;
       String address;
       double balance; 
      }
  </code></pre>
  
  <p>Then, let's say I write another class that uses this "Account" class, like the following:</p>
  
  <pre><code>    class UseAccount
      {
          public static void main(String[] args)
          {
              Account myAccount = new Account();
              Account yourAccount = new Account();
  
              myAccount.name = "Blah blah"
          }        
      }
  </code></pre>
  
  <p>etc., etc.</p>
  
  <p>When I write <code>myAccount.name = "Blah blah"</code>, I am changing the value of the variable "name" in the "Account" class.  I am free to do this as many times as I like with the code written the way it is.  It has come to my attention, however, that it's better practice to make the variables in the "Account" class private, and then use "setter" and "getter" methods.  So if I write the following:</p>
  
  <pre><code>    public class Account
      {
         private String name;
         private String address;
         private String balance;
  
         public void setName(String n)
         {
            name = n;
         }
  
         public String getName()
         {
            return name;
         }
      }
  </code></pre>
  
  <p>I can still change the value of the variable "name" by just creating another class that has something like:</p>
  
  <pre><code>    class UseAccount
      {
         public static void main(String[] args)
         {
            Account myAccount = new Account();
  
            myAccount.setName("Blah blah");
         }
      }
  </code></pre>
  
  <p>I don't understand how using this method is any different or is supposed to prevent people form changing the value of a private field.  Any help?</p>