Track dispatch after reassignment

A Java worker program uses the classes and client statements below. Each new object begins with its own units field equal to 2. Track both the selected method and the changing object state. What is the final value of total? Give an exact integer.


Java
class Job {
    int units = 2;

    int work() {
        units += 1;
        return units;
    }
}

class FastJob extends Job {
    int work() {
        units += 2;
        return 3 * units;
    }
}


The following statements run inside a method:


Java
Job first = new FastJob();
Job second = first;
int total = first.work();
first = new Job();
total += first.work();
total += second.work();


The first and second references initially point to one FastJob object whose units field is two.


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: