Pages

Sunday, October 2, 2016

Objects With Eyes That Age (Java)

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

class ObjectWithEyesThatAges extends ObjectThatAges {
  String eyeColor;
  ObjectWithEyesThatAges(String EyeColor) {
    super();
    this.eyeColor = EyeColor;
  }

class CreateObjectsThatAge {
  public static void output(ObjectThatAges obj) {
    System.out.println("Age of object (ms): " + obj.ageInMs());
  }
  public static void main(String[] args) {
    ObjectWithEyesThatAges first = new ObjectWithEyesThatAges("blue");
    ObjectThatAges last = new ObjectWithEyesThatAges("brown");
    for (int i=0; i<1000000; i++) {
      last = new ObjectThatAges();
    }
    output(first);
    output(last);
  }
}

The Wikipedia article Polymorphism (computer science) retrieved on 3 October 2016 describes different types of polymorphism and says that subtyping (also called subtype polymorphism or inclusion polymorphism) is:
when a name denotes instances of many different classes related by some common superclass. In the object-oriented programming community, this is often simply referred to as polymorphism.
Can you spot an example of subtype polymorphism in the Java code above?

Notice how the program above can be compiled and interpreted multiple times to produce data. What's interesting about the data shown in the image below? How does this data compare to the data produced by running the analogous JavaScript code presented in Objects That Age (Java)?