Homework 03: Classes, Objects, Methods

Submit this homework using Gradescope. You can type up your answers, or write legibly and scan them. Do not attempt to submit a paper copy in class, as it will not be accepted.


A. (1 point) Write a minimal definition for a class named MonthYear. Your answer to this question should be just the minimal definition.

B. (2 points) Add a constructor for MonthYear that takes a month and year (of the appropriate primitive type), and stores these values in immutable instance variables.

If the month or year is obviously invalid, then your constructor should throw an IllegalArgumentException. Do not exhaustively check correctness. Instead, limit your checks to checking for a non-negative year and a month between 1 and 12.

Your answer should be the entire class definition.

C. (1 point) Write a public toString() method with an appropriate signature that converts the MonthYear object to a String representation as exemplified by January 1978.

Your answer should be just the toString() method.


D. (3 points) Given the following code, what is the output? Assume a setNumber() method sets a relevant instance variable, and a equals() method that uses only this instance variable to check if two Bus objects values’ are equal.

Bus busA = new Bus();
Bus busB = new Bus();

busA.setNumber(44);
busB.setNumber(44);

System.out.println(busA == busB);
System.out.println(busA.equals(busB));

Bus busC = busB;
busB = busA;

busA.setNumber(13);

System.out.println(busA == busC);
System.out.println(busA.equals(busC));

busC = busB;

System.out.println(busA == busC);
System.out.println(busA.equals(busC));