File tree 3 files changed +61
-1
lines changed
3 files changed +61
-1
lines changed Original file line number Diff line number Diff line change
1
+ package interfaces ;
2
+
3
+ /*
4
+ * 假设希望使用Arrays类的sort方法对Employee对象数组进行排序,
5
+ * Employee类就必须实现Comparable接口
6
+ *
7
+ * 为了让类实现一个接口,通常需要下面几个步骤:
8
+ * 1. 将类声明为实现给定的接口
9
+ * 2. 让接口中的所有方法进行定义
10
+ */
11
+ public class Employee implements Comparable <Employee > {
12
+ private String name ;
13
+ private double salary ;
14
+
15
+ public Employee (String n , double s ) {
16
+ name = n ;
17
+ salary = s ;
18
+ }
19
+
20
+ public String getName () {
21
+ return name ;
22
+ }
23
+
24
+ public double getSalary () {
25
+ return salary ;
26
+ }
27
+
28
+ public void raiseSalary (double byPercent ) {
29
+ double raise = salary * byPercent / 100 ;
30
+ salary += raise ;
31
+ }
32
+
33
+ /* 在这里实现了需要提供的compareTo方法 */
34
+ public int compareTo (Employee other ) {
35
+ return Double .compare (salary , other .salary );
36
+ }
37
+ }
Original file line number Diff line number Diff line change
1
+ package interfaces ;
2
+
3
+ import java .util .*;
4
+
5
+ public class EmployeeSortTest {
6
+ public static void main (String [] args ) {
7
+ Employee [] staff = new Employee [3 ];
8
+
9
+ staff [0 ] = new Employee ("Harry Hacker" , 35000 );
10
+ staff [1 ] = new Employee ("Carl Cracker" , 75000 );
11
+ staff [2 ] = new Employee ("Tony Tester" , 38000 );
12
+
13
+ Arrays .sort (staff );
14
+
15
+ for (Employee e : staff )
16
+ System .out .println ("name=" + e .getName () + ",salary=" + e .getSalary ());
17
+ }
18
+ }
Original file line number Diff line number Diff line change 52
52
|----- ConstructorTest(重载)
53
53
54
54
55
- Part5(继承,2014年04月23日 -- ? )
55
+ Part5(继承,已完成 )
56
56
|
57
57
| ----- inheritance(继承初探)
58
58
|
63
63
| ----- arrayList(数组列表)
64
64
|
65
65
| ----- enums(枚举类)
66
+
67
+
68
+ Part6(接口与内部类,2014年05月02日 -- ?)
69
+ |
70
+ | ----- interfaces(接口)
66
71
|
67
72
| ----- ...
You can’t perform that action at this time.
0 commit comments