Here is a link to the Infant class. While Comparable is supposed to capture the
ID: 3627474 • Letter: H
Question
Here is a link to the Infant class.
While Comparable is supposed to capture the natural ordering for a class, it's possible to imagine unnatural orderings as well. So: in the box provided below, reimplement the compareTo() method so that one Infant is less than another, if the length of his or her name is less than the other.
public class Infant implements Comparable {
private String name;
private int age; // in months
public Infant(String who, int months) {
name = who;
age = months;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void anotherMonth() {
age = age + 1;
}
public int compareTo(Object other) {
put your code here
} //end method
} //end class
Explanation / Answer
public int compareTo(Object other){ String firstName = ((Infant)other).getName(); String secondName = this.name; return(fristName.length-secondName.length); }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.