Pages

Saturday, October 1, 2016

Objects That Age (Java)

class ObjectThatAges {
  long createDate;
  ObjectThatAges() {
    this.createDate = System.currentTimeMillis();
  }
  long ageInMs() {
    return System.currentTimeMillis() - this.createDate;
  }
}

Think about ways you could use objects constructed by ObjectThatAges. Ponder the following code snippet, for example.
ObjectThatAges first = new ObjectThatAges();
ObjectThatAges last = new ObjectThatAges();
for (int i=0; i<1000000; i++) {
  last = new ObjectThatAges();
}
long ageOfFirst = first.ageInMs();
long ageOfLast = last.ageInMs();
System.out.println(ageOfFirst);
System.out.println(ageOfLast);

See also: Objects With Eyes That Age (Java)