繼承:子類通過關鍵字extends指明其父類,從而建立類的繼承關系。
要點:
1)Java要求每個類都有父類,如果定義類時沒指明父類,默認為Object類。
2)java只持單超類繼承。也就是一個子只能有一個父,但一個父可以有多個子。
3)子類繼承父類非私有的數據成員和非私有的成員函數(體現(xiàn)出java的封裝性)。
4)子類除了繼承父類非私有的屬性外,還可添加子類自己特有的屬性。
1 //父類
2 class FatherDemo {
3 // 父親的公有屬性
4 public String usePen;
5
6 // 父親的公有方法
7 public void teach() {
8 System.out.println(usePen);
9 }
10 }
11
12 // 兒子類
13 class SonDemo extends FatherDemo {
14 // 添加特有的屬性
15 public String hobby;
16
17 // 添加特有方法
18 void selfStudy() {
19 System.out.println(hobby);
20 }
21 }
22
23 // 孫子類
24 class GrandsonDemo extends SonDemo {
25 // 添加特有的屬性
26 public String lazy;
27
28 // 添加特有方法
29 void study() {
30 System.out.println(lazy);
31 }
32 }
33
34 public class ExtendDemo {
35
36 public static void main(String[] args) {
37 FatherDemo father = new FatherDemo();
38 SonDemo son = new SonDemo();
39 GrandsonDemo grandson = new GrandsonDemo();
40 // 父自己的方法
41 System.out.println("father:");
42 father.usePen = "I can use a pen.";
43 father.teach();
44 System.out.println();
45 // 子繼承方法加自己的方法
46 System.out.println("son:");
47 son.usePen = "I can use a pen too.";
48 son.hobby = "I like football.";
49 son.teach();
50 son.selfStudy();
51 System.out.println();
52 // 孫繼承方法加自己的方法
53 System.out.println("grandson:");
54 grandson.usePen = "I can't use a pen.";
55 grandson.hobby = "I don't like football.";
56 grandson.lazy = "I am very lazy.";
57 grandson.teach();
58 grandson.selfStudy();
59 grandson.study();
60 }
61
62 }
2 class FatherDemo {
3 // 父親的公有屬性
4 public String usePen;
5
6 // 父親的公有方法
7 public void teach() {
8 System.out.println(usePen);
9 }
10 }
11
12 // 兒子類
13 class SonDemo extends FatherDemo {
14 // 添加特有的屬性
15 public String hobby;
16
17 // 添加特有方法
18 void selfStudy() {
19 System.out.println(hobby);
20 }
21 }
22
23 // 孫子類
24 class GrandsonDemo extends SonDemo {
25 // 添加特有的屬性
26 public String lazy;
27
28 // 添加特有方法
29 void study() {
30 System.out.println(lazy);
31 }
32 }
33
34 public class ExtendDemo {
35
36 public static void main(String[] args) {
37 FatherDemo father = new FatherDemo();
38 SonDemo son = new SonDemo();
39 GrandsonDemo grandson = new GrandsonDemo();
40 // 父自己的方法
41 System.out.println("father:");
42 father.usePen = "I can use a pen.";
43 father.teach();
44 System.out.println();
45 // 子繼承方法加自己的方法
46 System.out.println("son:");
47 son.usePen = "I can use a pen too.";
48 son.hobby = "I like football.";
49 son.teach();
50 son.selfStudy();
51 System.out.println();
52 // 孫繼承方法加自己的方法
53 System.out.println("grandson:");
54 grandson.usePen = "I can't use a pen.";
55 grandson.hobby = "I don't like football.";
56 grandson.lazy = "I am very lazy.";
57 grandson.teach();
58 grandson.selfStudy();
59 grandson.study();
60 }
61
62 }
輸出結果如下:
father:
I can use a pen.
son:
I can use a pen too.
I like football.
grandson:
I can't use a pen.
I don't like football.
I am very lazy.