?1
class
?Component1
{
?2
?
public
?Component1(
int
?i)
{
?3
?System.out.println(
"
Component1
"
);
?4
?}
?5
}
?6
?7
class
?Component2
{
?8
?
public
?Component2(
int
?i)
{
?9
?System.out.println(
"
Compunent2
"
);
10
?}
11
}
12
13
class
?Component3
{
14
?
public
?Component3(
int
?i)
{
15
?System.out.println(
"
Compunent3
"
);
16
?}
17
}
18
19
class
?Root
{
20
?
private
?
int
?i;
21
?Component1?com1
=
new
?Component1(i);
22
?Component2?com2
=
new
?Component2(i);
23
?Component3?com3
=
new
?Component3(i);
24
?
public
?Root(
int
?i)
{
25
?
this
.i
=
i;
26
?System.out.println(com1);?
//
(2)
27
?System.out.println(
"
Root
"
);
28
?}
29
?
public
?String?toString()
{?
return
?
"
Root
"
;}
30
?
public
?
void
?print()
{System.out.println(
"
Root
"
);}
31
}
32
33
public
?
class
?Stem?
extends
?Root
{
34
?
private
?
int
?i;
35
?Component1?com1
=
new
?Component1(i);
36
?Component2?com2
=
new
?Component2(i);
37
?Component3?com3
=
new
?Component3(i);
38
?
public
?Stem(
int
?i)
{
39
?
super
(i);
40
?
this
.i
=
i;
41
?System.out.println(com1);?
//
(1)
42
?System.out.println(
"
Stem
"
);
43
?}
44
?
public
?String?toString()
{?
return
?
"
Stem
"
;}
45
?
public
?
void
?print()
{System.out.println(
"
Stem
"
);}
46
?
public
?
static
?
void
?main(String[]?args)
{
47
?
//
Stem?st=new?Stem(10);?
//
(1)
48
?Root?st
=
new
?Stem(
10
);?
//
(2)
49
?System.out.println(st.com1);
//
(1)?這里的com1是Stem中的Component1對象
50
?
//
(2)?這里的com1是Root中的Component1對象
51
?
52
?System.out.println(st);
//
向下轉型了
53
?st.print();
//
向下轉型了
54
?}
55
}
56
這里可以看出,就st對象的類型來取得相應類的成員變量!


?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

好像只有在用到成員方法才會自動向下轉型,而成員變量卻不會!