Skip to content

Commit e50aa87

Browse files
committed
完成interfaces
1 parent 8796b40 commit e50aa87

File tree

3 files changed

+61
-1
lines changed

3 files changed

+61
-1
lines changed

Part6/interfaces/Employee.java

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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+
}
+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
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+
}

README

+6-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252
|----- ConstructorTest(重载)
5353

5454

55-
Part5(继承,2014年04月23日 -- ?
55+
Part5(继承,已完成
5656
|
5757
| ----- inheritance(继承初探)
5858
|
@@ -63,5 +63,10 @@
6363
| ----- arrayList(数组列表)
6464
|
6565
| ----- enums(枚举类)
66+
67+
68+
Part6(接口与内部类,2014年05月02日 -- ?)
69+
|
70+
| ----- interfaces(接口)
6671
|
6772
| ----- ...

0 commit comments

Comments
 (0)