Thursday, January 5, 2012

Static vs. Instance Methods

Static vs. Instance Methods

  • Static methods can access only static data and invoke other static methods.
    • Often serve as helper procedures/functions
    • Use when the desire is to provide a utility or access to class data only
  • Instance methods can access both instance and static data and methods.
    • Implement behavior for individual objects
    • Use when access to instance data/methods is required
  • An example of static method use is Java’s Math class.
    • All of its functionality is provided as static methods implementing mathematical functions (e.g., Math.sin()).
    • The Math class is designed so that you don’t (and can’t) create actual Math instances.
  • Static methods also are used to implement factory methods for creating objects, a technique discussed later in this class.
class Employee {
    String name;
    String ssn;
    String emailAddress;
    int yearOfBirth;
    int extraVacationDays = 0;
    static int baseVacationDays = 10;

    Employee(String name, String ssn) {
        this.name = name;
        this.ssn = ssn;
    }

    static void setBaseVacationDays(int days) {
        baseVacationDays = days < 10? 10 : days;
    }

    static int getBaseVacationDays() {
        return baseVacationDays;
    }

    void setExtraVacationDays(int days) {
        extraVacationDays = days < 0? 0 : days;
    }

    int getExtraVacationDays() {
        return extraVacationDays;
    }

    void setYearOfBirth(int year) {
        yearOfBirth = year;
    }

    int getVacationDays() {
        return baseVacationDays + extraVacationDays;
    }

    void print() {
        System.out.println("Name: " + name);
        System.out.println("SSN: " + ssn);
        System.out.println("Email Address: " + emailAddress);
        System.out.println("Year Of Birth: " + yearOfBirth);
        System.out.println("Vacation Days: " + getVacationDays());
    }
}
To change the company vacation policy, do Employee.setBaseVacationDays(15);
To give one employee extra vacation, do e2.setExtraVacationDays(5);

No comments: