释放双眼,带上耳机,听听看~!
- 一定要将数据设计为私有
- 一定要对数据初始化
- 不要在类中使用过多的基本数据类型
- 不是所有的域都需要独立的域访问器和域更改器
- 使用标准格式进行类的定义;按照
公有,包作用域,私有的顺序;每一部分中,要按照
实例方法,静态方法,实例域,静态域的顺序列出来。
- 将职责过多的类进行分解
- 类名和方法要能够体现他们的职责
下面一个测试程序,测试了重载构造器,调用另一构造器,默认构造器,对象初始化块,静态初始化块,实例域初始化等特性。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108 1package com.xujin;
2
3import java.util.Random;
4
5/**
6 * @author GinSmile
7 * @version 1.0
8 * A <code>Test</code> object to test some syntax
9 *
10 * default constructor
11 * overloaded constructor
12 * instance field initialization
13 * static initialization block
14 * object initialization block
15 * */
16public class Test {
17 public static void main(String[] args) {
18 Employee[] staff = new Employee[2];
19 staff[0] = new Employee("Bob", 1000);
20 staff[1] = new Employee("Jim", 2000);
21
22 System.out.println(staff[0].getBonus());//可能是12000.0
23 System.out.println(staff[1].getBonus());//可能是13000.0
24 }
25}
26
27class Employee{
28 //默认构造器
29 public Employee(){
30 //name initialized to ""
31 //salary initialized to 0.0
32 //id initialized to 0
33 //bonus initialized to 0.0
34 }
35
36 //重载构造器
37 public Employee(String name){
38 this.name = name;
39 id = nextId;
40 nextId++;
41 }
42
43 public Employee(String name, double salary){
44 this(name);//调用另一构造器
45 this.salary = salary;
46 }
47
48 //定义访问器方法
49 public String getName(){
50 return name;
51 }
52
53 public double getSalary(){
54 return salary;
55 }
56
57 public int getId(){
58 return id;
59 }
60
61 public double getBonus(){
62 return bonus;
63 }
64
65 //定义更改器方法
66 public void setName(String name){
67 this.name = name;
68 }
69
70 public void setSalary(double salary){
71 this.salary = salary;
72 }
73
74 public void setBonus(double bonus){
75 this.bonus = bonus;
76 }
77
78 /**
79 * Raise the salary of an employee
80 * @param percent the pecentage by which to raise the salary(0.1 means 10%)
81 * @return void
82 * */
83 public void raiseSalary(double percent){
84 this.salary *= (1 + percent);
85 }
86
87 //定义变量
88 private String name = "";//实例域初始化
89 private double salary;
90 private int id;
91 private static int nextId = 1;
92 private double bonus;
93
94 //静态初始化块,仅在类第一次加载的时候执行
95 static
96 {
97 Random ran = new Random();
98 nextId = ran.nextInt(100);
99 }
100
101 //对象初始化块,先于构造器执行
102 {
103 bonus = 1000 * nextId;
104 }
105
106
107}
108