6.1 接口不是类,是对类的一组需求的描述,这些类需要遵守接口描述的统一格式进行定义。例如:Arrays类中sort方法(可以对对象数组进行排序)前提是对象所属的类必须实现了Comparable 接口。
public interface Comparable { int compareTo(Object other) }
public interface Comparable<T> { int compareTo(T other) }
接口的方法自动的属于public;接口中可以定义多个方法;可以定义常量;接口不能含有实例域;
实现接口:1)将类声明为实现给定的接口(implements);2)对接口中的所有方法进行定义。
comparaTo 方法实现
1 public int ComparaTo(Object otherObject) 2 { 3 Employee other (Employee) otherObject; 4 return Double.compare(salary, other.salary); 5 }
静态Double.compare方法(第一个参数<第二个参数,返回一个负数,二者相等,返回0,
comparaTo 方法 泛型实现
1 class Employee implements Comparable<Employee>{ 2 public int ComparaTo(Employee other) 3 { 4 return Double.compare(salary, other.salary); 5 }
}
注意 Object 参数进行类型转换
为什么不在Employee类直接提供一个comparableTo方法呢?主要原因在于java是一种强类型(strongly typed)语言。在调用方法时编译器会检查这个方法是否存在。
1 package cc.openhome; 2 import java.util.Arrays; 3 public class JieKou { 4 public static void main(String[] args) { 5 // TODO code application logic here 6 Employee[] staff =new Employee[3]; 7 staff[0] =new Employee("harry Hacker", 75000); 8 staff[1]=new Employee("Carl Cracker", 355000); 9 staff[2]=new Employee("Tony Tester", 228000); 10 Arrays.sort(staff); 11 for(Employee e:staff) 12 System.out.println("name="+e.getName()+",salarry="+e.getSalary()); 13 } 14 } 15 class Employee implements Comparable<Employee> 16 { 17 private String name; 18 private double salary; 19 public Employee(String name,double salary) 20 { 21 this.name =name; 22 this.salary=salary; 23 } 24 public String getName() 25 { 26 return name ; 27 } 28 public double getSalary() 29 { 30 return salary; 31 } 32 public void raiseSalary(double byPercent) 33 { 34 double raise =salary*byPercent/100; 35 salary +=raise; 36 } 37 public int compareTo(Employee other) 38 { 39 return Double.compare(salary,other.salary); 40 } 41 }
name=harry Hacker,salarry=75000.0 name=Tony Tester,salarry=228000.0 name=Carl Cracker,salarry=355000.0 成功构建 (总时间: 0 秒)