1:子類方法優先檢索并使用子類的方法
2:子類與父類的屬性都是存在,引用類型是父類時就使用父類屬性,是子類就使用子類屬性
3
:調用父類方法(super.method()),父類方法中:
調用方法,優先搜索子類中是否有該方法,然后是父類的;
調用屬性,則是使用父類的屬性。
1
class Tree {
2
int i = 3, j = 5;
3
4
public Tree() {
5
this.show("Tree");
6
}
7
8
protected void show(String s) {
9
System.out.println(s);
10
}
11
12
public void t() {
13
this.show("Tree, t");
14
System.out.println(this.i);
15
System.out.println(this.j);
16
}
17
}
18
19
class Leaf extends Tree {
20
int i = 10;
21
22
public Leaf () {
23
this.show("Leaf");
24
}
25
26
public void show(String s) {
27
System.out.println(s + "\t\tLeaf");
28
}
29
30
public void t() {
31
show("Leaf, t");
32
System.out.println(this.i);
33
System.out.println(this.j);
34
System.out.println();
35
super.t();
36
}
37
38
public static void main(String args[]) {
39
Leaf l = new Leaf();
40
l.t();
41
42
System.out.println("------------------");
43
System.out.println(l.i);
44
Tree t = new Leaf();
45
l = (Leaf) t;
46
System.out.println(t.i);
47
System.out.println(l.i);
48
}
49
}
50

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

打印結果:
Tree Leaf
Leaf Leaf
Leaf, t Leaf
10
5
Tree, t Leaf
3
5
------------------
10
Tree Leaf
Leaf Leaf
3
10