Practice Problems: Critiquing Nested Class Code – Issues to Note
Here are several issues with the attempted solution:
The onSameAlbum method (Song class) should take only one song as an input (comparing it to the this song).
The types are missing on the data created in the Examples class (marsalbum, etc).
test1 fails because the use of == in onSameAlbum checks whether the albums were created with the same call to new (i.e. are the same object), not whether the two album objects have the same contents. There are two album objects in this code, one from each use of new.
test2 fails because the Album constructor does not store its genre argument in the class’ genre field – the constructor parameter named genre masks the genre field in the class. Either using this.genre or a different name for the parameter would solve the problem.
This exercise points out some nuances around = operators in Java:
The == operator does not check whether objects have the same contents. We will learn how to do that check next week.
To compare two Strings, use the equals method (as in the hasRockMusic method).
A single = is not an operator that checks for equality. It is a different instruction that stores a value under a name (as we see in the constructors). We will talk more about = in week 2 of the course.