Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions source/ch6_definingclasses.ptx
Original file line number Diff line number Diff line change
Expand Up @@ -1073,6 +1073,49 @@ public int compareTo(Fraction other) { // compare this fraction with another fra
</program>
</listing>

<exercise label="java_comparable_interface_parsons">
<statement>
<p>
Rearrange the blocks to create a <c>Student</c> class that implements <c>Comparable&lt;Student&gt;</c>. The class should feature a <c>private double gpa</c> field and a <c>compareTo</c> method that compares students based on their GPA.
</p>
</statement>
<blocks>
<block order="1">
<choice correct="yes">
<cline>public class Student implements Comparable&lt;Student&gt; {</cline>
<cline> private double gpa;</cline>
</choice>
<choice correct="no">
<cline>public class Student extends Comparable&lt;Student&gt; {</cline>
<cline> public double gpa;</cline>
</choice>
</block>

<block order="2">
<cline> public Student(double gpa) {</cline>
<cline> this.gpa = gpa;</cline>
<cline> }</cline>
</block>

<block order="3">
<choice correct="yes">
<cline> public int compareTo(Student other) {</cline>
<cline> return Double.compare(this.gpa, other.gpa);</cline>
<cline> }</cline>
</choice>
<choice correct="no">
<cline> public boolean compareTo(Student other) {</cline>
<cline> return this.gpa - other.gpa;</cline>
<cline> }</cline>
</choice>
</block>

<block order="4">
<cline>}</cline>
</block>
</blocks>
</exercise>

</section>


Expand Down