OO Programming with Java


Primitives datatypes

Classes can integrate data (also known as the attributes of a class). This one is then shared, and usable only, by the operations of the class. The private modifier thus protect the data from possible mistakes that will be illustrated here.

  1. Adding data:
public class Person {
  private int birthyear; // VISIBILITY: public or not public ?
}
public class Demo {
  public static void main(String args[]) {
    Person p    = new Person();
    p.birthyear = 2005;
    System.out.println("Birthyear: "+ p.birthyear +"");
  }
}

a. The code leads to error: error: birthyear has private access (if classes does not belong to the same package)
b. Thus, changing to public ?

public static void main(String args[]) {
  Person p    = new Person();
  p.birthyear = -2005; // <= <= <=
  System.out.println("Birthyear: "+ p.birthyear +"");
}

12 - 17