Encapsulate Field

From CSSEMediaWiki
Revision as of 06:49, 6 October 2008 by Johannes Pagwiwoko (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Replace public fields (instance variables) with private fields and provide public accessors.

Original code:

 public class Person {
   public String name;
 }

Refactored:

 public class Person {
   private String name;
   
   public void setName(String newName) {
       name = newName;
   }
   
   public String getName() {
       return name;
   }
 }
Personal tools