Resolve nested job objects

A maintenance simulator uses Java objects to predict job durations in seconds. A Task returns its stored duration. A Parallel object models two jobs starting together and adds four seconds of overhead after both finish. A Repeat object models consecutive repetitions of its child job.


The following code fully specifies the model. Assume durations are exact and there are no other delays.


Java
class Work {
    int seconds() {
        return 0;
    }
}

class Task extends Work {
    int duration;

    Task(int duration) {
        this.duration = duration;
    }

    @Override
    int seconds() {
        return duration;
    }
}

class Parallel extends Work {
    Work left;
    Work right;

    Parallel(Work left, Work right) {
        this.left = left;
        this.right = right;
    }

    @Override
    int seconds() {
        return Math.max(left.seconds(), right.seconds()) + 4;
    }
}

class Repeat extends Work {
    Work child;
    int count;

    Repeat(Work child, int count) {
        this.child = child;
        this.count = count;
    }

    @Override
    int seconds() {
        return count * child.seconds();
    }
}

Work a = new Repeat(
    new Parallel(new Task(18), new Task(30)), 3);

Work b = new Parallel(
    new Repeat(new Task(18), 3), new Task(30));


Math.max returns the larger of its two arguments. The diagram shows the objects created by the final two statements. Each non-root box begins with the name of the stored reference pointing to that object.


Two object structures connect Repeat, Parallel and Task objects through their stored references.


Find the durations returned by a.seconds() and b.seconds(). Enter each answer in seconds as an exact integer.

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Polymorphism Questions: