接口不是类,是对类的一组需求描述
Comparable接口
eg. Arrays类的sort可以对对象数组排序,前提是对象所属的类必须实现Comparable接口。
public interface Comparable
{
int compareTo(Object other);
}
public class Employee implements Comparable<Employee>
{
private String name;
private double salary;
...
public int compareTo(Employee other)
{
return Double.compare(salary, other.salary);
}
}
public class Test
{
public static void main(String[] args)
{
Employee[] staff = new Employee[2];
staff[0] = new Employee("Tom", 10000);
staff[1] = new Employee("Jerry", 20000);
Arrays.sort(staff);
for (Employee e : staff)
System.out.println("name = " + e.getName() + ", salary = " + e.getSalary());
}
}
任何实现Comparable接口的类都需要包含compareTo方法。
- 接口中所有方法自动属于public,所以在接口中声明方法不用加关键字(Java SE 8中允许在接口增加静态方法)
- 接口中不能含有实例域,只能包含常量,接口里的域自动设为public static final
- 提供实例域和方法实现都由实现接口的类完成,可以将接口看成没有实例域的抽象类
类实现接口步骤
- 将类声明为实现给定的接口
- 对接口中所有方法进行定义,将方法声明为public