Published on

CS 3500 Day 3

Authors
  • avatar
    Name
    Jacob Aronoff
    Twitter

Object Oriented Design

We're back to talking about durations, and how we can make our own classes that we use basic operations on.

We want to be able to:

  • Compare
  • Add
  • Subtract
  • Check Equality

We're going to be talking about hashCode() and equals(Object other)

The comparable interface enforces compareTo, equals, and hashCode. The abstract class we'll design for Duration needs to have a conversion to seconds, a conversion to Hms (hours, minutes, seconds), and a way to add two durations to each other. To ensure immutability for our variables, use the final keyword. Now we're talking about proper case analysis in a constructor: how to be sure that the data you're getting in your constructor matches your invariants.

It's important to use try's and catch's to make sure the parameters are correct. The try block can be used when you want to test for parameters. Now we're getting into equality. Equality needs some basic things to be satisfied:

public boolean equals(Object that) {
    if (this == that) {
      return true;
    }

    if (! (that instanceof Duration)) {
      return false;
    }

    return ((Duration) that).inSeconds() == this.inSeconds();
  }

First, we check if this is equal to that. Then we check if that is a duration, so we can short circuit. If it gets past all of those tests, we then check if our seconds is equal to the other objects seconds. If we don't have that last line, the java compiler will almost always say two things aren't equal becaues it compares memory addresses.

That's it! Basically just more of the same towards the end of class. I'm not going to be in class for day 4, so I'm just going to make a post that day about whatever the lecture notes are on.