The 6.1 interface is not a class and is a description of a set of requirements for a class that needs to be defined in a uniform format that follows the interface description. For example, the sort method in the arrays class (which can sort an array of objects) assumes that the class to which the object belongs must implement the comparable interface.
Public Interface comparable{ int compareTo (Object Other)}
comparable
Public Interface Comparable<t>{ int compareTo (T Other)}
comparable generics
interface method automatically belongs to the public, the interface can define multiple methods, you can define constants, interfaces cannot contain instance fields;
Implement Interface: 1) Declare the class to implement the given interface (implements), and 2) define all the methods in the interface.
Comparato Method implementation
1 Public int Comparato (Object otherobject) 2 {3 Employee Other (employee) Otherobject; 4 return Double. Compare (salary, other.salary); 5 }
Static double. Compare method (First argument < second argument, returns a negative number, equals, returns 0,
Comparato method Generic Implementation
1 class Implements comparable<employee>{2publicint Comparato (Employee Other)3 {4 return Double. Compare (salary, other.salary); 5 }
}
Note the type conversion of the Object parameter
Why not provide a Comparableto method directly in the employee class? The main reason is that Java is a strongly typed (strongly typed) language. When the method is called, the compiler checks to see if the method exists.
1 PackageCc.openhome;2 Importjava.util.Arrays;3 Public classJiekou {4 Public Static voidMain (string[] args) {5 //TODO Code application logic here6employee[] Staff =NewEmployee[3];7Staff[0] =NewEmployee ("Harry Hacker", 75000);8staff[1]=NewEmployee ("Carl cracker", 355000);9staff[2]=NewEmployee ("Tony Tester", 228000);Ten Arrays.sort (staff); One for(Employee e:staff) ASystem.out.println ("Name=" +e.getname () + ", salarry=" +e.getsalary ()); - } - } the classEmployeeImplementsComparable<employee> - { - PrivateString name; - Private Doublesalary; + PublicEmployee (String name,Doublesalary) - { + This. Name =name; A This. salary=salary; at } - PublicString getName () - { - returnname; - } - Public Doublegetsalary () in { - returnsalary; to } + Public voidRaisesalary (Doublebypercent) - { the DoubleRaise =salary*bypercent/100; *Salary + =raise; $ }Panax Notoginseng Public intCompareTo (Employee other) - { the returnDouble.compare (salary,other.salary); + } A}
Name=harry hacker,salarry=75000.0name=tony tester,salarry=228000.0name=carl cracker,salarry= 355000.00 seconds)
Run:
Java Core Technology Volume One note 6.1 Interface lambda expression inner class