在平常的Java項目開發中,entity(實體類)是必不可少的,它們通常都有不少的屬性,並有相應的setter和getter方法。entity(實體類)的做用通常是和數據表作映射。因此快速寫出規範的entity(實體類)是java開發中一項必不可少的技能。html
在項目中寫實體類通常遵循下面的規範:java
一、根據你的設計,定義一組你須要的私有屬性。eclipse
二、根據這些屬性,建立它們的setter和getter方法。(eclipse等集成開發軟件能夠自動生成。具體怎麼生成?請自行百度。)ide
三、提供帶參數的構造器和無參數的構造器。this
四、重寫父類中的eauals()方法和hashcode()方法。(若是須要涉及到兩個對象之間的比較,這兩個功能很重要。)spa
五、實現序列化並賦予其一個版本號。設計
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
|
class
Student
implements
Serializable{
/**
* 版本號
*/
private
static
final
long
serialVersionUID = 1L;
//定義的私有屬性
private
int
id;
private
String name;
private
int
age;
private
double
score;
//無參數的構造器
public
Student(){
}
//有參數的構造器
public
Student(
int
id,String name,
int
age,
double
score){
this
.id = id;
this
.name = name;
this
.age = age;
this
.score = score;
}
//建立的setter和getter方法
public
int
getId() {
return
id;
}
public
void
setId(
int
id) {
this
.id = id;
}
public
String getName() {
return
name;
}
public
void
setName(String name) {
this
.name = name;
}
public
int
getAge() {
return
age;
}
public
void
setAge(
int
age) {
this
.age = age;
}
public
double
getScore() {
return
score;
}
public
void
setScore(
double
score) {
this
.score = score;
}
//因爲id對於學生這個類是惟一能夠標識的,因此重寫了父類中的id的hashCode()和equals()方法。
@Override
public
int
hashCode() {
final
int
prime =
31
;
int
result =
1
;
result = prime * result + id;
return
result;
}
@Override
public
boolean
equals(Object obj) {
if
(
this
== obj)
return
true
;
if
(obj ==
null
)
return
false
;
if
(getClass() != obj.getClass())
return
false
;
Student other = (Student) obj;
if
(id != other.id)
return
false
;
return
true
;
}
}
|
一個學生的Java實體類就基本完成了。code
原文來自http://www.javashuo.com/article/p-ewdgpxly-ed.html(講的很明白就借鑑了)htm