Site Search:

Apply encapsulation principles to a class


Back OCAJP


Instance variables with public, package, default access modifiers can be modified by other classes whatever they like. This is not good, you don't want other people to change your name, because you own your name. Java class encapsulates data with private access modifier, so only the owning class has access to the encapsulated field, and can decide what to do with it. For example, owning class could only has getName() method, don't have setName(String name) method, therefore other classes can still read the name, but they can not change it.

JavaBeans are reusable software components. JavaBeans achieve encapsulation with private instance variable and public setter/getters. Java defines a naming convention that is used in JavaBeans.
The following example conforms to this naming convention.

OCAJP>cat test.java 
class test {
  public static void main(String...args) {
    test t = new test();
    t.setInstanceVariable1(10);
    System.out.println(t.getInstanceVariable1());
    t.setInstanceVariable2(true);
    //System.out.println(t.getInstanceVariable2()); //error: cannot find symbol
    System.out.println(t.isInstanceVariable2());
  }
  //properties are private
  private int instanceVariable1;
  private boolean instanceVariable2;
  //Getter is public, start with "get" for non-boolean or "is" for boolean.
  public int getInstanceVariable1() {return instanceVariable1;}
  public boolean isInstanceVariable2() {return instanceVariable2;}
  //Setter is public, start with "set"
  public void setInstanceVariable1(int instanceVariable1) {this.instanceVariable1 = instanceVariable1;}
  public void setInstanceVariable2(boolean instanceVariable2) {this.instanceVariable2 = instanceVariable2;}
}
OCAJP>javac test.java 
OCAJP>java test
10
true


A common strategy of encapsulating data is to make a class immutable. Immutable classes have all the instance variables initialized in the constructor, then only provide getter method, but omit setter method.


OCAJP>cat test.java 
class test{
  public static void main(String...args) {
    student s = new student("Joe");
    student s1 = new student("Ray");
    System.out.println(s.getName());
    System.out.println(s1.getName());
  }
}

class student {
  private String name;
  public student(String name) {
    this.name = name;
  }
  String getName() {return name;}
}
OCAJP>javac test.java 
OCAJP>java test
Joe
Ray

Back OCAJP