Getters and Setters

The previous scheme of accessing an object's fields directly suffers from lack of abstraction, in that it presupposes that the quantity in question is represented directly in the object, and therefore accessible.

This will not always be the case.

Example:

Consider objects representing people. One thing we might wish to know about a person is his or her age. If we represent age as a field and access it as follows:

Person P;
P.age

This commits the implementor to always have that field present. However, age changes with time, so we'd have to be constantly updating Person records, even if there is no fundamental change in the person.

It would be better to store the date-of-birth and have the age computed from that, given today's date. In order to do this, age would be treated as a method, not as a field. To emphasize this, we might call it getAge().

Person P;
P.getAge()		// age getter

 

A possible implementation of getAge:

import java.util.Date;
class Person
{
String name;
Date dateOfBirth;
static final long msPerYear = 31536000000L;	// L means long
Person(String name, Date dateOfBirth)
  {
  this.name = name;
  this.dateOfBirth = dateOfBirth;
  }

 

int getAge()	// returns age in years
  {
  long ms = System.currentTimeMillis() - dateOfBirth.getTime();
  return ms/msPerYear;
  }
}

 

// Suppose that John was born Dec. 30, 1980
Person p = new Person("John", new Date(80, 12, 30));	 

 

p.getAge() should return 17 on Feb. 16, 1998

 

Note: Date requires the year be relative to 1900, yet the date stored cannot be before 1970. A correction quantity must be stored in the Person record to handle dates-of-birth before 1970.

Next Slide Previous Slide Contents