Java 的对象传递
举一个简单的例子说明一下
需求:通过关联两个类,使可以通过Person 对象获取所关联的 Car 类的对象中的数据
一个 Person 类,一个 Car 类,
==> Person 类
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
|
class
Person{
// 设置变量
private
int
pid;
private
String pname;
private
int
page;
private
Car carname;
// 多参构造方法
public
Person(String pname,
int
page){
this
.setPname(pname);
this
.setPage(page);
}
public
String getInfo(){
return
"姓名: "
+ getPname() +
"\r"
+
"年龄:"
+ getPage() +
"\r"
;
}
public
void
setCarName(Car carname){
this
.carname = carname;
}
public
Car getCarName(){
return
this
.carname;
}
public
void
setPname(String pname){
this
.pname = pname;
}
public
String getPname(){
return
this
.pname;
}
public
void
setPage(
int
page){
this
.page = page;
}
public
int
getPage(){
return
this
.page;
}
}
|
==> Car 类
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
|
class
Car{
private
String cname;
private
Person pname;
// 构造函数
public
Car(String cname){
this
.setCname(cname);
}
public
void
setPname(Person pname){
this
.pname = pname;
}
public
Person getPname(){
return
this
.pname;
}
public
void
setCname(String cname){
this
.cname = cname;
}
public
String getCname(){
return
this
.cname;
}
public
String getCarInfo(){
return
"车名:"
+ getCname();
}
}
|
==> 测试类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public
class
testDemo {
public
static
void
main(String[] args) {
Person p =
new
Person(
"Tom"
,
20
);
Car car =
new
Car(
"宝马"
);
p.setCarName(car);
car.setPname(p);
System.out.println(p.getInfo());
// 通过 Person 对象获取 其 Car 对象中的内容
System.out.println(p.getCarName().getCarInfo());
// 通过 Car 对象获取 Person 对象中的内容
System.out.println(car.getPname().getPname());
}
}
|
本文转自 菜鸟的征程 51CTO博客,原文链接:http://blog.51cto.com/songqinglong/2071878