开发者

Can't figure out a compilation error for simple Java app

开发者 https://www.devze.com 2023-02-14 21:07 出处:网络
This is the error I am getting: Error: The type Customer must implement the inherited abstract method java.lang.Comparable.compareTo(Customer)

This is the error I am getting: Error: The type Customer must implement the inherited abstract method java.lang.Comparable.compareTo(Customer)

I'm comparing it to some lab work that I did and it looks exactly the same, yet that compiled just fine. I'm not sure what's going on here.

Here is the code segment in question which, incidentally, was written by my professor:

class Customer implements Comparable<Customer>
{
 String name;
 double purchase;
 double rebate;

public Customer(String n, double p, double r)
{ name=n;
  purchase=p;
  rebate=r;
 } //end Constructor

 public Customer(String n)
 { 
  name=n;
 } //end Constructor

 public String toString()
 {
  return String.format("%-20s%10.2f%10.2f", name, purchase, rebate);
 }

 /*
  Here, define the method comparedTo of the Comparable
  interface s开发者_如何学JAVAo that an array of Customer objects can
  be sorted by customer name
 */
 public int comparedTo(Customer a)
{
return this.name.compareTo(a.name);
}   //end comparedTo

} //end class Customer

Oh, and here are the inclusions the professor included:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

Your help is greatly appreciated!


comparedTo should be compareTo.

The error says it all. ;p


As Steven correctly pointed out, the name of the method you were attempting to implement was misspelled. A great way to catch errors like that is the @Override annotation, like this:

@Override
public int comparedTo(Customer a)

This tells the compiler that you intended comparedTo() to override a method declared in a parent class. When the compiler doesn't find a comparedTo() method to override, it will tell you. As of Java 1.6, @Override can also be used on methods declared in interfaces.

0

精彩评论

暂无评论...
验证码 换一张
取 消