Search code examples
javaobjectinterfacecomparecompareto

How to resolve: compareTo >> cannot find symbol


This is for a homework assignment. However, I have coded the overwhelming part of my assignment. There is just this one roadblock. I am also new to Java, so my terminology may be a bit off.

So I have 5 types: Provided by teacher:

  • NameInterface, which is the interface file for Name
  • Name, which uses 2 private Strings, first & last, for first and last name
  • StudentInterface, which is the interface file for Student
  • StudentTest, which is main method used for testing

Mostly provided by teacher, I just have to fix compareTo(). Everything else like constructors, fields, etc is done:

  • Student, which uses fullName (which is a NameInterface) & String city

Name class has a compareTo() override that uses Java's built-in compareTo to compare this first & other first

  public int compareTo(Object other)
  {
  int result = last.compareTo(((Name)other).last);

  if (result == 0)
  {   
      // last names are equal; check first
     result = first.compareTo(((Name)other).first);
  }  // end if 

  return result; 
} // end compareTo

Student class has a compareTo() that uses Name class compareTo to compare this Name & other Name as well as this city & other city

  public int compareTo(Object other)
  {
  Student localStudent = (Student) other;
  int result = (fullName.getName()).compareTo((localStudent.getName()).getName());

  if (result == 0)
  {   
      // last names are equal; check first
     result = city.compareTo(localStudent.getCity());
  }  // end if 

  return result; 
  } // end compareTo

I try to call Student class's compareTo in StudentTest, but it says cannot find symbol.

  StudentInterface si = new Student();
  si.setCity("Kingston");
  NameInterface ni = new Name("Andrew","Pletch");
  si.setName(ni);

  StudentInterface si2 = new Student();
  si2.setCity("Kingston");
  NameInterface ni2 = new Name("Aram","Agajanian");
  si2.setName(ni2);
  System.out.println(" compare as (should be +ve) " + si.compareTo(si2));

error is:

StudentTest.java:27: error: cannot find symbol
  System.out.println(" compare as (should be +ve) " + si.compareTo(si2));        
                                                        ^
symbol:   method compareTo(StudentInterface)
location: variable si of type StudentInterface
1 error

My conclusion is that "Object other" does not comply with "StudentInterface". How can I resolve this? Thank you everyone.


Solution

  • Add compareTo to the interface. All methods used have to be represented on the type of the variable. si is of type StudentInterface, so you can only used methods declared on StudentInterface.