OO Programming with Java


Primitives datatypes

c. NO !
Always keep data private and add 'accessor' (getX) and/or 'modifier' (setX) operations to control access - this is called "encapsulation".

public class Person {
  private int birthyear;
  public void setBirthyear(int y) { // MODIFIER (check)
    if(y>0) birthyear=y;
    else birthyear= -y; 
    // alternative: 
    // else throw new Exception("Bad value");
  }
  public int getBirthyear() { return birthyear; }
  // See also derivated/computed attributes/properties
}
public class Demo {
  public static void main(String args[]) {
    Person p = new Person();
    p.setBirthyear(2005);
    System.out.println("Birthyear: "+ p.getBirthyear());
  }
}

Nb. An attribute can be put public if it is a constant marked as final.


13 - 17