学习笔记(二)--->《Java 8编程官方参考教程(第9版).pdf》:第七章到九章学习笔记

2023-06-12,,

注:本文声明事项。

本博文整理者:刘军

本博文出自于: 《Java8 编程官方参考教程》一书

声明:1:转载请标注出处。本文不得作为商业活动。若有违本之,则本人不负法律责任。违法者自负一切法律责任。

          2: 本书对应的jdk为 jdk8版本

          3:因为内容容量太大,编辑器无法承受于是给拆分了以下版本:

          《Java 8编程官方参考教程(第9版).pdf》学习笔记(一)--->第一章到六章学习笔记讲:java的历史和演变、Java概述、数据类型、变量和数组、运算符、控制语句、类 等内容             

  《Java 8编程官方参考教程(第9版).pdf》学习笔记(二)--->第七章九章学习笔记讲:java 方法、继承详解、包和接口

___________________________________________________________________________________________________________________________

《Java 8编程官方参考教程(第9版)》pdf 下载地址:http://pan.baidu.com/s/1o7Zp3Mq 密码:     33cf

____________________________________________________________________________________________________________

第7章 方法和类的深入分析

7.1 重载方法

  1 package Chap7;
2
3 /**
4 * Demonstrate method overloading.
5 *
6 * @ClassName: OverloadDemo
7 * @Description:
8 * @author 刘军/shall_liu (1136808529@qq.com)
9 * @date 2017年9月14日 上午12:15:21
10 *
11 */
12 class OverloadDemo {
13 void test() {
14 System.out.println("No parameters");
15 }
16
17 // Overload test for one integer parameter.
18 void test(int a) {
19 System.out.println("a: " + a);
20 }
21
22 // Overload test for two integer parameters.
23 void test(int a, int b) {
24 System.out.println("a and b: " + a + " " + b);
25 }
26
27 // overload test for a double parameter
28 double test(double a) {
29 System.out.println("double a: " + a);
30 return a * a;
31 }
32 }
33
34
35 package Chap7;
36
37 /**
38 *
39 * @ClassName: Overload
40 * @Description:
41 * @author 刘军/shall_liu (1136808529@qq.com)
42 * @date 2017年9月14日 下午11:35:25
43 *
44 */
45 class Overload {
46 public static void main(String args[]) {
47 OverloadDemo ob = new OverloadDemo();
48 double result;
49
50 // call all versions of test()
51 ob.test();
52 ob.test(10);
53 ob.test(10, 20);
54 result = ob.test(123.25);
55 System.out.println("Result of ob.test(123.25): " + result);
56 }
57 }
58 //其运行结果为:
59 No parameters
60 a: 10
61 a and b: 10 20
62 double a: 123.25
63 Result of ob.test(123.25): 15190.5625
64
65
66
67

  1 package Chap7;
2
3 /**
4 * Demonstrate method overloading.
5 *
6 * @ClassName: OverloadDemo
7 * @Description:
8 * @author 刘军/shall_liu (1136808529@qq.com)
9 * @date 2017年9月14日 上午12:15:21
10 *
11 */
12 class OverloadDemo {
13 void test() {
14 System.out.println("No parameters");
15 }
16
17 // Overload test for two integer parameters.
18 void test(int a, int b) {
19 System.out.println("a and b: " + a + " " + b);
20 }
21
22 // overload test for a double parameter and return type
23 void test(double a) {
24 System.out.println("Inside test(double) a: " + a);
25 }
26 }
27
28 package Chap7;
29
30 /**
31 *
32 * @ClassName: Overload
33 * @Description:
34 * @author 刘军/shall_liu (1136808529@qq.com)
35 * @date 2017年9月14日 下午11:35:25
36 *
37 */
38 class Overload {
39 public static void main(String args[]) {
40 OverloadDemo ob = new OverloadDemo();
41 int i = 88;
42
43 ob.test();
44 ob.test(10, 20);
45
46 ob.test(i); // this will invoke test(double)
47 ob.test(123.2); // this will invoke test(double)
48 }
49 }
50 //其运行结果为:
51 No parameters
52 a and b: 10 20
53 Inside test(double) a: 88.0
54 Inside test(double) a: 123.2
55

7.1.1 重载构造函数

  1 package Chap7;
2
3 /**
4 *
5 * @ClassName: Box
6 * @Description: 重载构造器
7 * @author 刘军/shall_liu (1136808529@qq.com)
8 * @date 2017年9月14日 下午11:47:01
9 *
10 */
11 class Box {
12 double width;
13 double height;
14 double depth;
15
16 // This is the constructor for Box.
17 Box(double w, double h, double d) {
18 width = w;
19 height = h;
20 depth = d;
21 }
22
23 // compute and return volume
24 double volume() {
25 return width * height * depth;
26 }
27 }

  1 package Chap7;
2
3 /**
4 *
5 * @ClassName: Box
6 * @Description: 重载构造器
7 * Here, Box defines three constructors to initialize the dimensions of a box
8 * various ways.
9 * @author 刘军/shall_liu (1136808529@qq.com)
10 * @date 2017年9月14日 下午11:47:01
11 *
12 */
13 class Box {
14 double width;
15 double height;
16 double depth;
17
18 // constructor used when all dimensions specified
19 Box(double w, double h, double d) {
20 width = w;
21 height = h;
22 depth = d;
23 }
24
25 // constructor used when no dimensions specified
26 Box() {
27 width = -1; // use -1 to indicate
28 height = -1; // an uninitialized
29 depth = -1; // box
30 }
31
32 // constructor used when cube is created
33 Box(double len) {
34 width = height = depth = len;
35 }
36
37 // compute and return volume
38 double volume() {
39 return width * height * depth;
40 }
41 }
42
43
44
45 package Chap7;
46
47 /**
48 *
49 * @ClassName: OverloadCons
50 * @Description: 重载构造器
51 * @author 刘军/shall_liu (1136808529@qq.com)
52 * @date 2017年9月14日 下午11:49:30
53 *
54 */
55
56 class OverloadCons {
57 public static void main(String args[]) {
58 // create boxes using the various constructors
59 Box mybox1 = new Box(10, 20, 15);
60 Box mybox2 = new Box();
61 Box mycube = new Box(7);
62
63 double vol;
64
65 // get volume of first box
66 vol = mybox1.volume();
67 System.out.println("Volume of mybox1 is " + vol);
68
69 // get volume of second box
70 vol = mybox2.volume();
71 System.out.println("Volume of mybox2 is " + vol);
72
73 // get volume of cube
74 vol = mycube.volume();
75 System.out.println("Volume of mycube is " + vol);
76 }
77 }
78
79 //其运行结果为:
80 Volume of mybox1 is 3000.0
81 Volume of mybox2 is -1.0
82 Volume of mycube is 343.0
83
84
85

7.2 将对象用作参数

  1 class PassOb {
2 public static void main(String args[]) {
3 Test ob1 = new Test(100, 22);
4 Test ob2 = new Test(100, 22);
5 Test ob3 = new Test(-1, -1);
6
7 System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));
8
9 System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));
10 }
11 }
12
13 package Chap7;
14
15 /**
16 * Objects may be passed to methods.
17 *
18 * @ClassName: Test
19 * @Description:
20 * @author 刘军/shall_liu (1136808529@qq.com)
21 * @date 2017年9月14日 下午11:52:55
22 *
23 */
24 class Test {
25 int a, b;
26
27 Test(int i, int j) {
28 a = i;
29 b = j;
30 }
31
32 // return true if o is equal to the invoking object
33 boolean equalTo(Test o) {
34 if (o.a == a && o.b == b)
35 return true;
36 else
37 return false;
38 }
39 }
40 //其运行结果为:
41 ob1 == ob2: true
42 ob1 == ob3: false
43

  1 package Chap7;
2
3 /**
4 * Here, Box allows one object to initialize another.
5 *
6 * @ClassName: Box
7 * @Description:
8 * @author 刘军/shall_liu (1136808529@qq.com)
9 * @date 2017年9月15日 上午12:00:54
10 *
11 */
12
13 class Box {
14 double width;
15 double height;
16 double depth;
17
18 // construct clone of an object
19 Box(Box ob) { // pass object to constructor
20 width = ob.width;
21 height = ob.height;
22 depth = ob.depth;
23 }
24
25 // constructor used when all dimensions specified
26 Box(double w, double h, double d) {
27 width = w;
28 height = h;
29 depth = d;
30 }
31
32 // constructor used when no dimensions specified
33 Box() {
34 width = -1; // use -1 to indicate
35 height = -1; // an uninitialized
36 depth = -1; // box
37 }
38
39 // constructor used when cube is created
40 Box(double len) {
41 width = height = depth = len;
42 }
43
44 // compute and return volume
45 double volume() {
46 return width * height * depth;
47 }
48 }
49
50 package Chap7;
51
52 /**
53 *
54 * @ClassName: OverloadCons2
55 * @Description:
56 * @author 刘军/shall_liu (1136808529@qq.com)
57 * @date 2017年9月15日 上午12:01:21
58 *
59 */
60 class OverloadCons2 {
61 public static void main(String args[]) {
62 // create boxes using the various constructors
63 Box mybox1 = new Box(10, 20, 15);
64 Box mybox2 = new Box();
65 Box mycube = new Box(7);
66
67 Box myclone = new Box(mybox1);
68
69 double vol;
70
71 // get volume of first box
72 vol = mybox1.volume();
73 System.out.println("Volume of mybox1 is " + vol);
74
75 // get volume of second box
76 vol = mybox2.volume();
77 System.out.println("Volume of mybox2 is " + vol);
78
79 // get volume of cube
80 vol = mycube.volume();
81 System.out.println("Volume of cube is " + vol);
82
83 // get volume of clone
84 vol = myclone.volume();
85 System.out.println("Volume of clone is " + vol);
86 }
87 }
88
89
90 //其运行结果为:
91 Volume of mybox1 is 3000.0
92 Volume of mybox2 is -1.0
93 Volume of cube is 343.0
94 Volume of clone is 3000.0
95
96
97

7.3 参数传递的深入分析

  1 package Chap7;
2
3 /**
4 * Objects may be passed to methods.
5 *
6 * @ClassName: Test
7 * @Description:
8 * @author 刘军/shall_liu (1136808529@qq.com)
9 * @date 2017年9月14日 下午11:52:55
10 *
11 */
12 // Simple Types are passed by value.
13 class Test {
14 void meth(int i, int j) {
15 i *= 2;
16 j /= 2;
17 }
18 }
19
20 package Chap7;
21
22 class CallByValue {
23 public static void main(String args[]) {
24 Test ob = new Test();
25 int a = 15, b = 20;
26
27 System.out.println("a and b before call: " + a + " " + b);
28
29 ob.meth(a, b);
30
31 System.out.println("a and b after call: " + a + " " + b);
32 }
33 }
34
35 //其运行结果为:、
36 a and b before call: 15 20
37 a and b after call: 15 20
38
39

  1 package Chap7;
2
3 /**
4 * Objects are passed through their references.
5 *
6 * @ClassName: Test
7 * @Description:
8 * @author 刘军/shall_liu (1136808529@qq.com)
9 * @date 2017年9月14日 下午11:52:55
10 *
11 */
12
13 class Test {
14 int a, b;
15
16 Test(int i, int j) {
17 a = i;
18 b = j;
19 }
20
21 // pass an object
22 void meth(Test o) {
23 o.a *= 2;
24 o.b /= 2;
25 }
26 }
27
28
29 package Chap7;
30
31 /**
32 *
33 * @ClassName: PassObjRef
34 * @Description:
35 * @author 刘军/shall_liu (1136808529@qq.com)
36 * @date 2017年9月15日 上午12:10:14
37 *
38 */
39 class PassObjRef {
40 public static void main(String args[]) {
41 Test ob = new Test(15, 20);
42
43 System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b);
44
45 ob.meth(ob);
46
47 System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b);
48 }
49 }
50
51 //其运行结果为;
52 ob.a and ob.b before call: 15 20
53 ob.a and ob.b after call: 30 10
54

7.4 返回对象

  1 package Chap7;
2
3 /**
4 * Objects are passed through their references.
5 *
6 * @ClassName: Test
7 * @Description:
8 * @author 刘军/shall_liu (1136808529@qq.com)
9 * @date 2017年9月14日 下午11:52:55
10 *
11 */
12
13 class Test {
14 int a, b;
15
16
17 public Test() {
18 }
19
20 Test(int i) {
21 a = i;
22 }
23
24 Test(int i, int j) {
25 a = i;
26 b = j;
27 }
28
29 // pass an object
30 void meth(Test o) {
31 o.a *= 2;
32 o.b /= 2;
33 }
34
35 Test incrByTen() {
36 Test temp = new Test(a + 10);
37 return temp;
38 }
39 }
40
41
42
43 package Chap7;
44
45 class RetOb {
46 public static void main(String args[]) {
47 Test ob1 = new Test(2);
48 Test ob2;
49
50 ob2 = ob1.incrByTen();
51 System.out.println("ob1.a: " + ob1.a);
52 System.out.println("ob2.a: " + ob2.a);
53
54 ob2 = ob2.incrByTen();
55 System.out.println("ob2.a after second increase: " + ob2.a);
56 }
57 }
58
59 //
60 ob1.a: 2
61 ob2.a: 12
62 ob2.a after second increase: 22
63
64
65

7.5 递归

  1 package Chap7;
2
3 //A simple example of recursion.
4 class Factorial {
5 // this is a recusive function
6 int fact(int n) {
7 int result;
8
9 if (n == 1)
10 return 1;
11 result = fact(n - 1) * n;
12 return result;
13 }
14 }
15
16
17 package Chap7;
18
19 class Recursion {
20 public static void main(String args[]) {
21 Factorial f = new Factorial();
22
23 System.out.println("Factorial of 3 is " + f.fact(3));
24 System.out.println("Factorial of 4 is " + f.fact(4));
25 System.out.println("Factorial of 5 is " + f.fact(5));
26 }
27 }
28 //
29
30
31 Factorial of 3 is 6
32 Factorial of 4 is 24
33 Factorial of 5 is 120
34

  1 package Chap7;
2
3 //Another example that uses recursion.
4
5 class RecTest {
6 int values[];
7
8 RecTest(int i) {
9 values = new int[i];
10 }
11
12 // display arrary -- recursively
13 void printArray(int i) {
14 if (i == 0)
15 return;
16 else
17 printArray(i - 1);
18 System.out.println("[" + (i - 1) + "] " + values[i - 1]);
19 }
20 }
21
22 package Chap7;
23
24 class Recursion2 {
25 public static void main(String args[]) {
26 RecTest ob = new RecTest(10);
27 int i;
28
29 for (i = 0; i < 10; i++)
30 ob.values[i] = i;
31
32 ob.printArray(10);
33 }
34 }
35
36 //
37 [0] 0
38 [1] 1
39 [2] 2
40 [3] 3
41 [4] 4
42 [5] 5
43 [6] 6
44 [7] 7
45 [8] 8
46 [9] 9
47
48

7.6 访问控制

  1 package Chap7;
2
3 /* This program demonstrates the difference between
4 public and private.
5 */
6 class Test {
7 int a; // default access
8 public int b; // public access
9 private int c; // private access
10
11 // methods to access c
12 void setc(int i) { // set c's value
13 c = i;
14 }
15
16 int getc() { // get c's value
17 return c;
18 }
19 }
20
21
22 package Chap7;
23
24 class AccessTest {
25 public static void main(String args[]) {
26 Test ob = new Test();
27
28 // These are OK, a and b may be accessed directly
29 ob.a = 10;
30 ob.b = 20;
31
32 // This is not OK and will cause an error
33 // ob.c = 100; // Error!
34
35 // You must access c through its methods
36 ob.setc(100); // OK
37
38 System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc());
39 }
40 }
41 //
42
43 a, b, and c: 10 20 100
44
45
46

  1 package Chap7;
2
3 //This class defines an integer stack that can hold 10 values.
4 class Stack {
5 /*
6 * Now, both stck and tos are private. This means that they cannot be
7 * accidentally or maliciously altered in a way that would be harmful to the
8 * stack.
9 */
10 private int stck[] = new int[10];
11 private int tos;
12
13 // Initialize top-of-stack
14 Stack() {
15 tos = -1;
16 }
17
18 // Push an item onto the stack
19 void push(int item) {
20 if (tos == 9)
21 System.out.println("Stack is full.");
22 else
23 stck[++tos] = item;
24 }
25
26 // Pop an item from the stack
27 int pop() {
28 if (tos < 0) {
29 System.out.println("Stack underflow.");
30 return 0;
31 } else
32 return stck[tos--];
33 }
34 }
35

  1 class TestStack {
2 public static void main(String args[]) {
3 Stack mystack1 = new Stack();
4 Stack mystack2 = new Stack();
5
6 // push some numbers onto the stack
7 for(int i=0; i<10; i++) mystack1.push(i);
8 for(int i=10; i<20; i++) mystack2.push(i);
9
10 // pop those numbers off the stack
11 System.out.println("Stack in mystack1:");
12 for(int i=0; i<10; i++)
13 System.out.println(mystack1.pop());
14
15 System.out.println("Stack in mystack2:");
16 for(int i=0; i<10; i++)
17 System.out.println(mystack2.pop());
18
19 // these statements are not legal
20 // mystack1.tos = -2;
21 // mystack2.stck[3] = 100;
22 }
23 }

7.7 理解st

  1 // Demonstrate static variables, methods, and blocks.
2 class UseStatic {
3 static int a = 3;
4 static int b;
5
6 static void meth(int x) {
7 System.out.println("x = " + x);
8 System.out.println("a = " + a);
9 System.out.println("b = " + b);
10 }
11
12 static {
13 System.out.println("Static block initialized.");
14 b = a * 4;
15 }
16
17 public static void main(String args[]) {
18 meth(42);
19 }
20 }

  1 class StaticDemo {
2 static int a = 42;
3 static int b = 99;
4 static void callme() {
5 System.out.println("a = " + a);
6 }
7 }
8
9 class StaticByName {
10 public static void main(String args[]) {
11 StaticDemo.callme();
12 System.out.println("b = " + StaticDemo.b);
13 }
14 }
15

7.8 final介绍

7.9 重新审视数组

  1 // This program demonstrates the length array member.
2 class Length {
3 public static void main(String args[]) {
4 int a1[] = new int[10];
5 int a2[] = {3, 5, 7, 1, 8, 99, 44, -10};
6 int a3[] = {4, 3, 2, 1};
7
8 System.out.println("length of a1 is " + a1.length);
9 System.out.println("length of a2 is " + a2.length);
10 System.out.println("length of a3 is " + a3.length);
11 }
12 }
13

  1 // Improved Stack class that uses the length array member.
2 class Stack {
3 private int stck[];
4 private int tos;
5
6 // allocate and initialize stack
7 Stack(int size) {
8 stck = new int[size];
9 tos = -1;
10 }
11
12 // Push an item onto the stack
13 void push(int item) {
14 if(tos==stck.length-1) // use length member
15 System.out.println("Stack is full.");
16 else
17 stck[++tos] = item;
18 }
19
20 // Pop an item from the stack
21 int pop() {
22 if(tos < 0) {
23 System.out.println("Stack underflow.");
24 return 0;
25 }
26 else
27 return stck[tos--];
28 }
29 }

  1 class TestStack2 {
2 public static void main(String args[]) {
3 Stack mystack1 = new Stack(5);
4 Stack mystack2 = new Stack(8);
5
6 // push some numbers onto the stack
7 for(int i=0; i<5; i++) mystack1.push(i);
8 for(int i=0; i<8; i++) mystack2.push(i);
9
10 // pop those numbers off the stack
11 System.out.println("Stack in mystack1:");
12 for(int i=0; i<5; i++)
13 System.out.println(mystack1.pop());
14
15 System.out.println("Stack in mystack2:");
16 for(int i=0; i<8; i++)
17 System.out.println(mystack2.pop());
18 }
19 }

7.10 嵌套类和内部类

  1 // Demonstrate an inner class.
2 class Outer {
3 int outer_x = 100;
4
5 void test() {
6 Inner inner = new Inner();
7 inner.display();
8 }
9
10 // this is an innner class
11 class Inner {
12 void display() {
13 System.out.println("display: outer_x = " + outer_x);
14 }
15 }
16 }
17
18 class InnerClassDemo {
19 public static void main(String args[]) {
20 Outer outer = new Outer();
21 outer.test();
22 }
23 }
24

  1 // This program will not compile.
2 class Outer {
3 int outer_x = 100;
4
5 void test() {
6 Inner inner = new Inner();
7 inner.display();
8 }
9
10 // this is an innner class
11 class Inner {
12 int y = 10; // y is local to Inner
13 void display() {
14 System.out.println("display: outer_x = " + outer_x);
15 }
16 }
17
18 void showy() {
19 System.out.println(y); // error, y not known here!
20 }
21 }
22
23 class InnerClassDemo {
24 public static void main(String args[]) {
25 Outer outer = new Outer();
26 outer.test();
27 }
28 }
29

  1
2 // Define an inner class within a for loop.
3 class Outer {
4 int outer_x = 100;
5
6 void test() {
7 for(int i=0; i<10; i++) {
8 class Inner {
9 void display() {
10 System.out.println("display: outer_x = " + outer_x);
11 }
12 }
13 Inner inner = new Inner();
14 inner.display();
15 }
16 }
17 }
18
19 class InnerClassDemo {
20 public static void main(String args[]) {
21 Outer outer = new Outer();
22 outer.test();
23 }
24 }
25

7.11 String类介绍

  1 // Demonstrating Strings.
2 class StringDemo {
3 public static void main(String args[]) {
4 String strOb1 = "First String";
5 String strOb2 = "Second String";
6 String strOb3 = strOb1 + " and " + strOb2;
7
8 System.out.println(strOb1);
9 System.out.println(strOb2);
10 System.out.println(strOb3);
11 }
12 }

  1 // Demonstrating some String methods.
2 class StringDemo2 {
3 public static void main(String args[]) {
4 String strOb1 = "First String";
5 String strOb2 = "Second String";
6 String strOb3 = strOb1;
7
8 System.out.println("Length of strOb1: " + strOb1.length());
9
10 System.out.println("Char at index 3 in strOb1: " + strOb1.charAt(3));
11
12 if(strOb1.equals(strOb2)) {
13 System.out.println("strOb1 == strOb2");
14 }else{
15 System.out.println("strOb1 != strOb2");
16 }
17
18 if(strOb1.equals(strOb3)) {
19 System.out.println("strOb1 == strOb3");}
20 else{
21 System.out.println("strOb1 != strOb3");}
22 }
23 }
24

  1 // Demonstrate String arrays.
2 class StringDemo3 {
3 public static void main(String args[]) {
4 String str[] = { "one", "two", "three" };
5
6 for(int i=0; i<str.length; i++)
7 System.out.println("str[" + i + "]: " + str[i]);
8 }
9 }
10

7.12 使用命令行参数

  1 class CommandLine {
2 public static void main(String args[]) {
3 for(int i=0; i<args.length; i++)
4 System.out.println("args[" + i + "]: " + args[i]);
5 }
6 }
7

7.13 varargs:可变长度参数

  1 // Use an array to pass a variable number of
2 // arguments to a method.
3 class PassArray {
4 static void vaTest(int v[]) {
5 System.out.print("Number of args: " + v.length + " Contents: ");
6
7 for(int x : v){
8 System.out.print(x + " ");
9 }
10 System.out.println();
11 }
12
13 public static void main(String args[])
14 {
15 // Notice how an array must be created to
16 // hold the arguments.
17 int n1[] = { 10 };
18 int n2[] = { 1, 2, 3 };
19 int n3[] = { };
20
21 vaTest(n1); // 1 arg
22 vaTest(n2); // 3 args
23 vaTest(n3); // no args
24 }
25 }

  1 // Demonstrate variable-length arguments.
2 class VarArgs {
3
4 // vaTest() now uses a vararg.
5 static void vaTest(int ... v) {
6 System.out.print("Number of args: " + v.length + " Contents: ");
7
8 for(int x : v) {
9 System.out.print(x + " ");
10 }
11 System.out.println();
12 }
13
14 public static void main(String args[])
15 {
16
17 // Notice how vaTest() can be called with a
18 // variable number of arguments.
19 vaTest(10); // 1 arg
20 vaTest(1, 2, 3); // 3 args
21 vaTest(); // no args
22 }
23 }
24

  1 // Use varargs with standard arguments.
2 class VarArgs2 {
3
4 // Here, msg is a normal parameter and v is a
5 // varargs parameter.
6 static void vaTest(String msg, int ... v) {
7 System.out.print(msg + v.length +
8 " Contents: ");
9
10 for(int x : v) {
11 System.out.print(x + " ");
12 }
13
14 System.out.println();
15 }
16
17 public static void main(String args[])
18 {
19 vaTest("One vararg: ", 10);
20 vaTest("Three varargs: ", 1, 2, 3);
21 vaTest("No varargs: ");
22 }
23 }
24

7.13.1 重载varargs方法

  1 // Varargs and overloading.
2 class VarArgs3 {
3
4 static void vaTest(int ... v) {
5 System.out.print("vaTest(int ...): " + "Number of args: " + v.length + " Contents: ");
6
7 for(int x : v) {
8 System.out.print(x + " ");
9 }
10 System.out.println();
11 }
12
13 static void vaTest(boolean ... v) {
14 System.out.print("vaTest(boolean ...) " + "Number of args: " + v.length + " Contents: ");
15
16 for(boolean x : v) {
17 System.out.print(x + " ");
18 }
19 System.out.println();
20 }
21
22 static void vaTest(String msg, int ... v) {
23 System.out.print("vaTest(String, int ...): " + msg + v.length + " Contents: ");
24
25 for(int x : v) {
26 System.out.print(x + " ");
27 }
28 System.out.println();
29 }
30
31 public static void main(String args[])
32 {
33 vaTest(1, 2, 3);
34 vaTest("Testing: ", 10, 20);
35 vaTest(true, false, false);
36

7.13.2 varargs方法与模糊性

  1 // Varargs, overloading, and ambiguity.
2 //
3 // This program contains an error and will
4 // not compile!
5 class VarArgs4 {
6
7 static void vaTest(int ... v) {
8 System.out.print("vaTest(Integer ...): " + "Number of args: " + v.length + " Contents: ");
9
10 for(int x : v) {
11 System.out.print(x + " ");
12 }
13 System.out.println();
14 }
15
16 static void vaTest(boolean ... v) {
17 System.out.print("vaTest(boolean ...) " + "Number of args: " + v.length + " Contents: ");
18
19 for(boolean x : v) {
20 System.out.print(x + " ");
21 }
22 System.out.println();
23 }
24
25
26 public static void main(String args[])
27 {
28 vaTest(1, 2, 3); // OK
29 vaTest(true, false, false); // OK
30
31 vaTest(); // Error: Ambiguous!
32 }
33 }

第8章 继承

8.1 继承的基础知识

  1 // A simple example of inheritance.
2
3 // Create a superclass.
4 class A {
5 int i, j;
6
7 void showij() {
8 System.out.println("i and j: " + i + " " + j);
9 }
10 }
11
12 // Create a subclass by extending class A.
13 class B extends A {
14 int k;
15
16 void showk() {
17 System.out.println("k: " + k);
18 }
19 void sum() {
20 System.out.println("i+j+k: " + (i+j+k));
21 }
22 }
23
24 class SimpleInheritance {
25 public static void main(String args[]) {
26 A superOb = new A();
27 B subOb = new B();
28
29 // The superclass may be used by itself.
30 superOb.i = 10;
31 superOb.j = 20;
32 System.out.println("Contents of superOb: ");
33 superOb.showij();
34 System.out.println();
35
36 /* The subclass has access to all public members of
37 its superclass. */
38 subOb.i = 7;
39 subOb.j = 8;
40 subOb.k = 9;
41 System.out.println("Contents of subOb: ");
42 subOb.showij();
43 subOb.showk();
44 System.out.println();
45
46 System.out.println("Sum of i, j and k in subOb:");
47 subOb.sum();
48 }
49 }
50

8.1.1 成员访问与继承

  1 /* In a class hierarchy, private members remain
2 private to their class.
3
4 This program contains an error and will not
5 compile.
6 */
7
8 // Create a superclass.
9 class A {
10 int i; // public be default
11 private int j; // private to A
12
13 void setij(int x, int y) {
14 i = x;
15 j = y;
16 }
17 }
18
19 // A's j is not accessible here.
20 class B extends A {
21 int total;
22
23 void sum() {
24 total = i + j; // ERROR, j is not accessible here
25 }
26 }
27
28 class Access {
29 public static void main(String args[]) {
30 B subOb = new B();
31
32 subOb.setij(10, 12);
33
34 subOb.sum();
35 System.out.println("Total is " + subOb.total);
36 }
37 }
38

8.1.2 一个更实际的例子

  1 // This program uses inheritance to extend Box.
2 class Box {
3 double width;
4 double height;
5 double depth;
6
7 // construct clone of an object
8 Box(Box ob) { // pass object to constructor
9 width = ob.width;
10 height = ob.height;
11 depth = ob.depth;
12 }
13
14 // constructor used when all dimensions specified
15 Box(double w, double h, double d) {
16 width = w;
17 height = h;
18 depth = d;
19 }
20
21 // constructor used when no dimensions specified
22 Box() {
23 width = -1; // use -1 to indicate
24 height = -1; // an uninitialized
25 depth = -1; // box
26 }
27
28 // constructor used when cube is created
29 Box(double len) {
30 width = height = depth = len;
31 }
32
33 // compute and return volume
34 double volume() {
35 return width * height * depth;
36 }
37 }
38
39 // Here, Box is extened to include weight.
40 class BoxWeight extends Box {
41 double weight; // weight of box
42
43 // constructor for BoxWeight
44 BoxWeight(double w, double h, double d, double m) {
45 width = w;
46 height = h;
47 depth = d;
48 weight = m;
49 }
50 }
51
52 class DemoBoxWeight {
53 public static void main(String args[]) {
54 BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
55 BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
56 double vol;
57
58 vol = mybox1.volume();
59 System.out.println("Volume of mybox1 is " + vol);
60 System.out.println("Weight of mybox1 is " + mybox1.weight);
61 System.out.println();
62
63 vol = mybox2.volume();
64 System.out.println("Volume of mybox2 is " + vol);
65 System.out.println("Weight of mybox2 is " + mybox2.weight);
66 }
67 }
68

  1 // Here, Box is extended to include color.
2 class ColorBox extends Box {
3 int color; // color of box
4
5 ColorBox(double w, double h, double d, int c) {
6 width = w;
7 height = h;
8 depth = d;
9 color = c;
10 }
11 }
12

8.1.3 超类变量可以引用子类对象

  1 class RefDemo {
2 public static void main(String args[]) {
3 BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37);
4 Box plainbox = new Box();
5 double vol;
6
7 vol = weightbox.volume();
8 System.out.println("Volume of weightbox is " + vol);
9 System.out.println("Weight of weightbox is " + weightbox.weight);
10 System.out.println();
11
12 // assign BoxWeight reference to Box reference
13 plainbox = weightbox;
14
15 vol = plainbox.volume(); // OK, volume() defined in Box
16 System.out.println("Volume of plainbox is " + vol);
17
18 /* The following statement is invalid because plainbox
19 does not define a weight member. */
20 // System.out.println("Weight of plainbox is " + plainbox.weight);
21 }
22 }

8.2 使用super关键字

8.2.1 使用super调用超类的构造函数

  1 // BoxWeight now uses super to initialize its Box attributes.
2 class BoxWeight extends Box {
3 double weight; // weight of box
4
5 // initialize width, height, and depth using super()
6 BoxWeight(double w, double h, double d, double m) {
7 super(w, h, d); // call superclass constructor
8 weight = m;
9 }
10 }

  1  // A complete implementation of BoxWeight.
2 class Box {
3 private double width;
4 private double height;
5 private double depth;
6
7 // construct clone of an object
8 Box(Box ob) { // pass object to constructor
9 width double h, double d) {
10 width = w;
11 height = h;
12 depth = d;
13 }
14
15 // constructor used when no dimensions specified
16 Box() {
17 width = -1; // use -1 to indicate
18 height = -1; // an uninitialized
19 depth = -1; // box
20 }
21 = ob.width;
22 height = ob.height;
23 depth = ob.depth;
24 }
25
26 // constructor used when all dimensions specified
27 Box(double w,
28 // constructor used when cube is created
29 Box(double len) {
30 width = height = depth = len;
31 }
32
33 // compute and return volume
34 double volume() {
35 return width * height * depth;
36 }
37 }
38
39 // BoxWeight now fully implements all constructors.
40 class BoxWeight extends Box {
41 double weight; // weight of box
42
43 // construct clone of an object
44 BoxWeight(BoxWeight ob) { // pass object to constructor
45 super(ob);
46 weight = ob.weight;
47 }
48
49 // constructor when all parameters are specified
50 BoxWeight(double w, double h, double d, double m) {
51 super(w, h, d); // call superclass constructor
52 weight = m;
53 }
54
55 // default constructor
56 BoxWeight() {
57 super();
58 weight = -1;
59 }
60
61 // constructor used when cube is created
62 BoxWeight(double len, double m) {
63 super(len);
64 weight = m;
65 }
66 }
67
68 class DemoSuper {
69 public static void main(String args[]) {
70 BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
71 BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
72 BoxWeight mybox3 = new BoxWeight(); // default
73 BoxWeight mycube = new BoxWeight(3, 2);
74 BoxWeight myclone = new BoxWeight(mybox1);
75 double vol;
76
77 vol = mybox1.volume();
78 System.out.println("Volume of mybox1 is " + vol);
79 System.out.println("Weight of mybox1 is " + mybox1.weight);
80 System.out.println();
81
82 vol = mybox2.volume();
83 System.out.println("Volume of mybox2 is " + vol);
84 System.out.println("Weight of mybox2 is " + mybox2.weight);
85 System.out.println();
86
87 vol = mybox3.volume();
88 System.out.println("Volume of mybox3 is " + vol);
89 System.out.println("Weight of mybox3 is " + mybox3.weight);
90 System.out.println();
91
92 vol = myclone.volume();
93 System.out.println("Volume of myclone is " + vol);
94 System.out.println("Weight of myclone is " + myclone.weight);
95 System.out.println();
96
97 vol = mycube.volume();
98 System.out.println("Volume of mycube is " + vol);
99 System.out.println("Weight of mycube is " + mycube.weight);
100 System.out.println();
101 }
102 }
103

  1 // construct clone of an object
2 BoxWeight(BoxWeight ob) { // pass object to constructor
3 super(ob);
4 weight = ob.weight;
5 }
6

8.2.2 super的另一种用法

  1 // Using super to overcome name hiding.
2 class A {
3 int i;
4 }
5
6 // Create a subclass by extending class A.
7 class B extends A {
8 int i; // this i hides the i in A
9
10 B(int a, int b) {
11 super.i = a; // i in A
12 i = b; // i in B
13 }
14
15 void show() {
16 System.out.println("i in superclass: " + super.i);
17 System.out.println("i in subclass: " + i);
18 }
19 }
20
21 class UseSuper {
22 public static void main(String args[]) {
23 B subOb = new B(1, 2);
24
25 subOb.show();
26 }
27 }
28

8.3 创建多级继承层次

  1 // Extend BoxWeight to include shipping costs.
2
3 // Start with Box.
4 class Box {
5 private double width;
6 private double height;
7 private double depth;
8
9 // construct clone of an object
10 Box(Box ob) { // pass object to constructor
11 width = ob.width;
12 height = ob.height;
13 depth = ob.depth;
14 }
15
16 // constructor used when all dimensions specified
17 Box(double w, double h, double d) {
18 width = w;
19 height = h;
20 depth = d;
21 }
22
23 // constructor used when no dimensions specified
24 Box() {
25 width = -1; // use -1 to indicate
26 height = -1; // an uninitialized
27 depth = -1; // box
28 }
29
30 // constructor used when cube is created
31 Box(double len) {
32 width = height = depth = len;
33 }
34
35 // compute and return volume
36 double volume() {
37 return width * height * depth;
38 }
39 }
40
41 // Add weight.
42 class BoxWeight extends Box {
43 double weight; // weight of box
44
45 // construct clone of an object
46 BoxWeight(BoxWeight ob) { // pass object to constructor
47 super(ob);
48 weight = ob.weight;
49 }
50
51 // constructor when all parameters are specified
52 BoxWeight(double w, double h, double d, double m) {
53 super(w, h, d); // call superclass constructor
54 weight = m;
55 }
56
57 // default constructor
58 BoxWeight() {
59 super();
60 weight = -1;
61 }
62
63 // constructor used when cube is created
64 BoxWeight(double len, double m) {
65 super(len);
66 weight = m;
67 }
68 }
69
70 // Add shipping costs
71 class Shipment extends BoxWeight {
72 double cost;
73
74 // construct clone of an object
75 Shipment(Shipment ob) { // pass object to constructor
76 super(ob);
77 cost = ob.cost;
78 }
79
80 // constructor when all parameters are specified
81 Shipment(double w, double h, double d,
82 double m, double c) {
83 super(w, h, d, m); // call superclass constructor
84 cost = c;
85 }
86
87 // default constructor
88 Shipment() {
89 super();
90 cost = -1;
91 }
92
93 // constructor used when cube is created
94 Shipment(double len, double m, double c) {
95 super(len, m);
96 cost = c;
97 }
98 }
99
100 class DemoShipment {
101 public static void main(String args[]) {
102 Shipment shipment1 =
103 new Shipment(10, 20, 15, 10, 3.41);
104 Shipment shipment2 =
105 new Shipment(2, 3, 4, 0.76, 1.28);
106
107 double vol;
108
109 vol = shipment1.volume();
110 System.out.println("Volume of shipment1 is " + vol);
111 System.out.println("Weight of shipment1 is "
112

8.4 构造函数的调用时机

  1 // Demonstrate when constructors are called.
2
3 // Create a super class.
4 class A {
5 A() {
6 System.out.println("Inside A's constructor.");
7 }
8 }
9
10 // Create a subclass by extending class A.
11 class B extends A {
12 B() {
13 System.out.println("Inside B's constructor.");
14 }
15 }
16
17 // Create another subclass by extending B.
18 class C extends B {
19 C() {
20 System.out.println("Inside C's constructor.");
21 }
22 }
23
24 class CallingCons {
25 public static void main(String args[]) {
26 C c = new C();
27 }
28 }
29

8.5 方法重写

  1 // Method overriding.
2 class A {
3 int i, j;
4
5 A(int a, int b) {
6 i = a;
7 j = b;
8 }
9
10 // display i and j
11 void show() {
12 System.out.println("i and j: " + i + " " + j);
13 }
14 }
15
16 class B extends A {
17 int k;
18
19 B(int a, int b, int c) {
20 super(a, b);
21 k = c;
22 }
23
24 // display k -- this overrides show() in A
25 void show() {
26 System.out.println("k: " + k);
27 }
28 }
29
30 class Override {
31 public static void main(String args[]) {
32 B subOb = new B(1, 2, 3);
33
34 subOb.show(); // this calls show() in B
35 }
36 }
37

  1 class B extends A {
2 int k;
3
4 B(int a, int b, int c) {
5 super(a, b);
6 k = c;
7 }
8
9 void show() {
10 super.show(); // this calls A's show()
11 System.out.println("k: " + k);
12 }
13 }
14

  1 // Methods with differing type signatures are overloaded -- not overridden.
2 class A {
3 int i, j;
4
5 A(int a, int b) {
6 i = a;
7 j = b;
8 }
9
10 // display i and j
11 void show() {
12 System.out.println("i and j: " + i + " " + j);
13 }
14 }
15
16 // Create a subclass by extending class A.
17 class B extends A {
18 int k;
19
20 B(int a, int b, int c) {
21 super(a, b);
22 k = c;
23 }
24
25 // overload show()
26 void show(String msg) {
27 System.out.println(msg + k);
28 }
29 }
30
31 class Override {
32 public static void main(String args[]) {
33 B subOb = new B(1, 2, 3);
34
35 subOb.show("This is k: "); // this calls show() in B
36 subOb.show(); // this calls show() in A
37 }
38 }
39

8.6 动态方法调度

  1 // Dynamic Method Dispatch
2 class A {
3 void callme() {
4 System.out.println("Inside A's callme method");
5 }
6 }
7
8 class B extends A {
9 // override callme()
10 void callme() {
11 System.out.println("Inside B's callme method");
12 }
13 }
14
15 class C extends A {
16 // override callme()
17 void callme() {
18 System.out.println("Inside C's callme method");
19 }
20 }
21
22 class Dispatch {
23 public static void main(String args[]) {
24 A a = new A(); // object of type A
25 B b = new B(); // object of type B
26 C c = new C(); // object of type C
27 A r; // obtain a reference of type A
28
29 r = a; // r refers to an A object
30 r.callme(); // calls A's version of callme
31
32 r = b; // r refers to a B object
33 r.callme(); // calls B's version of callme
34
35 r = c; // r refers to a C object
36 r.callme(); // calls C's version of callme
37 }
38 }
39

8.6.1 重写方法的目的

8.6.2 应用方法重写

  1 // Using run-time polymorphism.
2 class Figure {
3 double dim1;
4 double dim2;
5
6 Figure(double a, double b) {
7 dim1 = a;
8 dim2 = b;
9 }
10
11 double area() {
12 System.out.println("Area for Figure is undefined.");
13 return 0;
14 }
15 }
16
17 class Rectangle extends Figure {
18 Rectangle(double a, double b) {
19 super(a, b);
20 }
21
22 // override area for rectangle
23 double area() {
24 System.out.println("Inside Area for Rectangle.");
25 return dim1 * dim2;
26 }
27 }
28
29 class Triangle extends Figure {
30 Triangle(double a, double b) {
31 super(a, b);
32 }
33
34 // override area for right triangle
35 double area() {
36 System.out.println("Inside Area for Triangle.");
37 return dim1 * dim2 / 2;
38 }
39 }
40
41 class FindAreas {
42 public static void main(String args[]) {
43 Figure f = new Figure(10, 10);
44 Rectangle r = new Rectangle(9, 5);
45 Triangle t = new Triangle(10, 8);
46
47 Figure figref;
48
49 figref = r;
50 System.out.println("Area is " + figref.area());
51
52 figref = t;
53 System.out.println("Area is " + figref.area());
54
55 figref = f;
56 System.out.println("Area is " + figref.area());
57 }
58 }
59

8.7 使用抽象类

  1 // A Simple demonstration of abstract.
2 abstract class A {
3 abstract void callme();
4
5 // concrete methods are still allowed in abstract classes
6 void callmetoo() {
7 System.out.println("This is a concrete method.");
8 }
9 }
10
11 class B extends A {
12 void callme() {
13 System.out.println("B's implementation of callme.");
14 }
15 }
16
17 class AbstractDemo {
18 public static void main(String args[]) {
19 B b = new B();
20
21 b.callme();
22 b.callmetoo();
23 }
24 }

  1 // Using abstract methods and classes.
2 abstract class Figure {
3 double dim1;
4 double dim2;
5
6 Figure(double a, double b) {
7 dim1 = a;
8 dim2 = b;
9 }
10
11 // area is now an an abstract method
12 abstract double area();
13 }
14
15 class Rectangle extends Figure {
16 Rectangle(double a, double b) {
17 super(a, b);
18 }
19
20 // override area for rectangle
21 double area() {
22 System.out.println("Inside Area for Rectangle.");
23 return dim1 * dim2;
24 }
25 }
26
27 class Triangle extends Figure {
28 Triangle(double a, double b) {
29 super(a, b);
30 }
31
32 // override area for right triangle
33 double area() {
34 System.out.println("Inside Area for Triangle.");
35 return dim1 * dim2 / 2;
36 }
37 }
38
39 class AbstractAreas {
40 public static void main(String args[]) {
41 // Figure f = new Figure(10, 10); // illegal now
42 Rectangle r = new Rectangle(9, 5);
43 Triangle t = new Triangle(10, 8);
44
45 Figure figref; // this is OK, no object is created
46
47 figref = r;
48 System.out.println("Area is " + figref.area());
49
50 figref = t;
51 System.out.println("Area is " + figref.area());
52 }
53 }

8.8 在继承中使用final关键字

8.8.1 使用final关键字阻止重写

  1 class A {
2 final void meth() {
3 System.out.println("This is a final method.");
4 }
5 }
6
7 class B extends A {
8 void meth() { // ERROR! Can't override.
9 System.out.println("Illegal!");
10 }
11 }
12

8.8.2 使用final关键字阻止继承

  1 final class A {
2 // ...
3 }
4
5 // The following class is illegal.
6 class B extends A { // ERROR! Can't subclass A
7 // ...
8 }

8.9 Object类

第9章 包和接口

9.1 包

9.1.1 定义包

9.1.2 包查找与CLASSPATH

9.1.3 一个简短的包示例

  1 // A simple package
2 package MyPack;
3
4 class Balance {
5 String name;
6 double bal;
7
8 Balance(String n, double b) {
9 name = n;
10 bal = b;
11 }
12
13 void show() {
14 if(bal<0)
15 System.out.print("-->> ");
16 System.out.println(name + ": $" + bal);
17 }
18 }
19
20 class AccountBalance {
21 public static void main(String args[]) {
22 Balance current[] = new Balance[3];
23
24 current[0] = new Balance("K. J. Fielding", 123.23);
25 current[1] = new Balance("Will Tell", 157.02);
26 current[2] = new Balance("Tom Jackson", -12.33);
27
28 for(int i=0; i<3; i++) current[i].show();
29 }
30 }

9.2 访问保护

  1 package p1;
2
3 public class Protection {
4 int n = 1;
5 private int n_pri = 2;
6 protected int n_pro = 3;
7 public int n_pub = 4;
8
9 public Protection() {
10 System.out.println("base constructor");
11 System.out.println("n = " + n);
12 System.out.println("n_pri = " + n_pri);
13 System.out.println("n_pro = " + n_pro);
14 System.out.println("n_pub = " + n_pub);
15 }
16 }
17
18 class Derived extends Protection {
19 Derived() {
20 System.out.println("derived constructor");
21 System.out.println("n = " + n);
22
23 // class only
24 // System.out.println("n_pri = " + n_pri);
25
26 System.out.println("n_pro = " + n_pro);
27 System.out.println("n_pub = " + n_pub);
28 }
29 }
30
31 class SamePackage {
32 SamePackage() {
33 Protection p = new Protection();
34 System.out.println("same package constructor");
35 System.out.println("n = " + p.n);
36
37 // class only
38 // System.out.println("n_pri = " + p.n_pri);
39
40 System.out.println("n_pro = " + p.n_pro);
41 System.out.println("n_pub = " + p.n_pub);
42 }
43 }
44

  1 package p2;
2
3 class Protection2 extends p1.Protection {
4 Protection2() {
5 System.out.println("derived other package constructor");
6
7 // class or package only
8 // System.out.println("n = " + n);
9
10 // class only
11 // System.out.println("n_pri = " + n_pri);
12
13 System.out.println("n_pro = " + n_pro);
14 System.out.println("n_pub = " + n_pub);
15 }
16 }
17
18 class OtherPackage {
19 OtherPackage() {
20 p1.Protection p = new p1.Protection();
21 System.out.println("other package constructor");
22
23 // class or package only
24 // System.out.println("n = " + p.n);
25
26 // class only
27 // System.out.println("n_pri = " + p.n_pri);
28
29 // class, subclass or package only
30 // System.out.println("n_pro = " + p.n_pro);
31
32 System.out.println("n_pub = " + p.n_pub);
33 }
34 }

  1 // Demo package p1.
2 package p1;
3
4 // Instantiate the various classes in p1.
5 public class Demo {
6 public static void main(String args[]) {
7 Protection ob1 = new Protection();
8 Derived ob2 = new Derived();
9 SamePackage ob3 = new SamePackage();
10 }
11 }
12

  1 // Demo package p2.
2 package p2;
3
4 // Instantiate the various classes in p2.
5 public class Demo {
6 public static void main(String args[]) {
7 Protection2 ob1 = new Protection2();
8 OtherPackage ob2 = new OtherPackage();
9 }
10 }
11

9.3 导入包

  1 package JavaBase_ReferenceNanual.Chap9.listing8.MyPack;
2
3 /**
4 * 项目名称:JavaEE_Base
5 * 类名称:Balance
6 * 类描述: Now, the Balance class, its constructor,
7 * and its show() method are public. This means that they can be used by
8 * non-subclass code outside their package.
9 * 创建人: shall_liu(1136808529@qq.com)
10 * 创建时间:2017年9月21日 上午12:01:36
11 * 修改人:amin
12 * 修改时间:2017年9月21日 上午12:01:36
13 * 修改备注:
14 * @version
15 */
16 public class Balance {
17 String name;
18 double bal;
19
20 public Balance(String n, double b) {
21 name = n;
22 bal = b;
23 }
24
25 public void show() {
26 if (bal < 0)
27 System.out.print("-->> ");
28 System.out.println(name + ": $" + bal);
29 }
30 }

  1 package JavaBase_ReferenceNanual.Chap9.listing9.MyPack;
2
3 import JavaBase_ReferenceNanual.Chap9.listing8.MyPack.*;
4 /**
5 *
6 *
7 * 项目名称:JavaEE_Base
8 * 类名称:TestBalance
9 * 类描述:
10 * 创建人: shall_liu(1136808529@qq.com)
11 * 创建时间:2017年9月21日 上午12:06:30
12 * 修改人:amin
13 * 修改时间:2017年9月21日 上午12:06:30
14 * 修改备注:
15 * @version
16 *
17 */
18 class TestBalance {
19 public static void main(String args[]) {
20
21 /* Because Balance is public, you may use Balance
22 class and call its constructor. */
23 Balance test = new Balance("J. J. Jaspers", 99.88);
24
25 test.show(); // you may also call show()
26 }
27 }
28

9.4 接口

9.4.1 定义接口

9.4.2 实现接口

  1 package JavaBase_ReferenceNanual.Chap9.listing9.MyPack;
2
3 import javax.security.auth.callback.Callback;
4
5 class Client implements Callback {
6 // Implement Callback's interface
7 public void callback(int p) {
8 System.out.println("callback called with " + p);
9 }
10
11 void nonIfaceMeth() {
12 System.out.println("Classes that implement interfaces " + "may also define other members, too.");
13 }
14 }
15
16 package JavaBase_ReferenceNanual.Chap9.listing9.MyPack;
17
18 import javax.security.auth.callback.Callback;
19 /**
20 *
21 *
22 * 项目名称:JavaEE_Base
23 * 类名称:TestIface
24 * 类描述:
25 * 创建人: shall_liu(1136808529@qq.com)
26 * 创建时间:2017年9月21日 上午1:00:06
27 * 修改人:amin
28 * 修改时间:2017年9月21日 上午1:00:06
29 * 修改备注:
30 * @version
31 *
32 */
33 class TestIface {
34 public static void main(String args[]) {
35 Callback c = new Client();
36 ((Client) c).callback(42);
37 }
38 }
39 //运行结果为
40 callback called with 42
41

  1 package JavaBase_ReferenceNanual.Chap9.listing9.MyPack;
2
3 import javax.security.auth.callback.Callback;
4
5 /**
6 *
7 *
8 * 项目名称:JavaEE_Base
9 * 类名称:AnotherClient
10 * 类描述: Another implementation of Callback.
11 * 创建人: shall_liu(1136808529@qq.com)
12 * 创建时间:2017年9月21日 上午1:03:26
13 * 修改人:amin
14 * 修改时间:2017年9月21日 上午1:03:26
15 * 修改备注:
16 * @version
17 *
18 */
19 class AnotherClient implements Callback {
20 // Implement Callback's interface
21 public void callback(int p) {
22 System.out.println("Another version of callback");
23 System.out.println("p squared is " + (p * p));
24 }
25 }
26
27
28 package JavaBase_ReferenceNanual.Chap9.listing9.MyPack;
29
30 import javax.security.auth.callback.Callback;
31
32 class Client implements Callback {
33 // Implement Callback's interface
34 public void callback(int p) {
35 System.out.println("callback called with " + p);
36 }
37
38 void nonIfaceMeth() {
39 System.out.println("Classes that implement interfaces " + "may also define other members, too.");
40 }
41 }
42
43 package JavaBase_ReferenceNanual.Chap9.listing9.MyPack;
44
45 import javax.security.auth.callback.Callback;
46
47 /**
48 *
49 *
50 * 项目名称:JavaEE_Base
51 * 类名称:TestIface2
52 * 类描述:
53 * 创建人: shall_liu(1136808529@qq.com)
54 * 创建时间:2017年9月21日 上午1:04:49
55 * 修改人:amin
56 * 修改时间:2017年9月21日 上午1:04:49
57 * 修改备注:
58 * @version
59 *
60 */
61
62 class TestIface2 {
63 public static void main(String args[]) {
64 Callback c = new Client();
65 AnotherClient ob = new AnotherClient();
66
67 ((Client) c).callback(42);
68
69 c = ob; // c now refers to AnotherClient object
70 ((Client) c).callback(42);
71 }
72 }
73

9.4.3 嵌套接口

  1 // A nested interface example.
2
3 // This class contains a member interface.
4 class A {
5 // this is a nested interface
6 public interface NestedIF {
7 boolean isNotNegative(int x);
8 }
9 }
10
11 // B implements the nested interface.
12 class B implements A.NestedIF {
13 public boolean isNotNegative(int x) {
14 return x < 0 ? false : true;
15 }
16 }
17
18 class NestedIFDemo {
19 public static void main(String args[]) {
20
21 // use a nested interface reference
22 A.NestedIF nif = new B();
23
24 if(nif.isNotNegative(10))
25 System.out.println("10 is not negative");
26 if(nif.isNotNegative(-12))
27 System.out.println("this won't be displayed");
28 }
29 }
30

9.4.4 应用接口

  1 // Define an integer stack interface.
2 interface IntStack {
3 void push(int item); // store an item
4 int pop(); // retrieve an item
5 }
6
7 // An implementation of IntStack that uses fixed storage.
8 class FixedStack implements IntStack {
9 private int stck[];
10 private int tos;
11
12 // allocate and initialize stack
13 FixedStack(int size) {
14 stck = new int[size];
15 tos = -1;
16 }
17
18 // Push an item onto the stack
19 public void push(int item) {
20 if(tos==stck.length-1) // use length member
21 System.out.println("Stack is full.");
22 else
23 stck[++tos] = item;
24 }
25
26 // Pop an item from the stack
27 public int pop() {
28 if(tos < 0) {
29 System.out.println("Stack underflow.");
30 return 0;
31 }
32 else
33 return stck[tos--];
34 }
35 }
36
37 class IFTest {
38 public static void main(String args[]) {
39 FixedStack mystack1 = new FixedStack(5);
40 FixedStack mystack2 = new FixedStack(8);
41
42 // push some numbers onto the stack
43 for(int i=0; i<5; i++) mystack1.push(i);
44 for(int i=0; i<8; i++) mystack2.push(i);
45
46 // pop those numbers off the stack
47 System.out.println("Stack in mystack1:");
48 for(int i=0; i<5; i++)
49 System.out.println(mystack1.pop());
50
51 System.out.println("Stack in mystack2:");
52 for(int i=0; i<8; i++)
53 System.out.println(mystack2.pop());
54 }
55 }

  1 // Define an integer stack interface.
2 interface IntStack {
3 void push(int item); // store an item
4 int pop(); // retrieve an item
5 }
6
7 // Implement a "growable" stack.
8 class DynStack implements IntStack {
9 private int stck[];
10 private int tos;
11
12 // allocate and initialize stack
13 DynStack(int size) {
14 stck = new int[size];
15 tos = -1;
16 }
17
18 // Push an item onto the stack
19 public void push(int item) {
20 // if stack is full, allocate a larger stack
21 if(tos==stck.length-1) {
22 int temp[] = new int[stck.length * 2]; // double size
23 for(int i=0; i<stck.length; i++) temp[i] = stck[i];
24 stck = temp;
25 stck[++tos] = item;
26 }
27 else
28 stck[++tos] = item;
29 }
30
31 // Pop an item from the stack
32 public int pop() {
33 if(tos < 0) {
34 System.out.println("Stack underflow.");
35 return 0;
36 }
37 else
38 return stck[tos--];
39 }
40 }
41
42 class IFTest2 {
43 public static void main(String args[]) {
44 DynStack mystack1 = new DynStack(5);
45 DynStack mystack2 = new DynStack(8);
46
47 // these loops cause each stack to grow
48 for(int i=0; i<12; i++) mystack1.push(i);
49 for(int i=0; i<20; i++) mystack2.push(i);
50
51 System.out.println("Stack in mystack1:");
52 for(int i=0; i<12; i++)
53 System.out.println(mystack1.pop());
54
55 System.out.println("Stack in mystack2:");
56 for(int i=0; i<20; i++)
57 System.out.println(mystack2.pop());
58 }
59 }
60

  1 /* Create an interface variable and
2 access stacks through it.
3 */
4 class IFTest3 {
5 public static void main(String args[]) {
6 IntStack mystack; // create an interface reference variable
7 DynStack ds = new DynStack(5);
8 FixedStack fs = new FixedStack(8);
9
10 mystack = ds; // load dynamic stack
11 // push some numbers onto the stack
12 for(int i=0; i<12; i++) mystack.push(i);
13
14 mystack = fs; // load fixed stack
15 for(int i=0; i<8; i++) mystack.push(i);
16
17
18 mystack = ds;
19 System.out.println("Values in dynamic stack:");
20 for(int i=0; i<12; i++)
21 System.out.println(mystack.pop());
22
23 mystack = fs;
24 System.out.println("Values in fixed stack:");
25 for(int i=0; i<8; i++)
26 System.out.println(mystack.pop());
27 }
28 }
29

9.4.5 接口中的变量

  1 import java.util.Random;
2
3 interface SharedConstants {
4 int NO = 0;
5 int YES = 1;
6 int MAYBE = 2;
7 int LATER = 3;
8 int SOON = 4;
9 int NEVER = 5;
10 }
11
12 class Question implements SharedConstants {
13 Random rand = new Random();
14 int ask() {
15 int prob = (int) (100 * rand.nextDouble());
16 if (prob < 30)
17 return NO; // 30%
18 else if (prob < 60)
19 return YES; // 30%
20 else if (prob < 75)
21 return LATER; // 15%
22 else if (prob < 98)
23 return SOON; // 13%
24 else
25 return NEVER; // 2%
26 }
27 }
28
29 class AskMe implements SharedConstants {
30 static void answer(int result) {
31 switch(result) {
32 case NO:
33 System.out.println("No");
34 break;
35 case YES:
36 System.out.println("Yes");
37 break;
38 case MAYBE:
39 System.out.println("Maybe");
40 break;
41 case LATER:
42 System.out.println("Later");
43 break;
44 case SOON:
45 System.out.println("Soon");
46 break;
47 case NEVER:
48 System.out.println("Never");
49 break;
50 }
51 }
52
53 public static void main(String args[]) {
54 Question q = new Question();
55 answer(q.ask());
56 answer(q.ask());
57 answer(q.ask());
58 answer(q.ask());
59 }
60 }

9.4.6 接口可以扩展

  1 // One interface an extend another.
2 interface A {
3 void meth1();
4 void meth2();
5 }
6
7 // B now includes meth1() and meth2() -- it adds meth3().
8 interface B extends A {
9 void meth3();
10 }
11
12 // This class must implement all of A and B
13 class MyClass implements B {
14 public void meth1() {
15 System.out.println("Implement meth1().");
16 }
17
18 public void meth2() {
19 System.out.println("Implement meth2().");
20 }
21
22 public void meth3() {
23 System.out.println("Implement meth3().");
24 }
25 }
26
27 class IFExtend {
28 public static void main(String arg[]) {
29 MyClass ob = new MyClass();
30
31 ob.meth1();
32 ob.meth2();
33 ob.meth3();
34 }
35 }

9.5 默认接口方法

9.5.1 默认方法的基础知识

  1 public interface MyIF {
2 // This is a "normal" interface method declaration.
3 // It does NOT define a default implementation.
4 int getNumber();
5
6 // This is a default method. Notice that it provides
7 // a default implementation.
8 default String getString() {
9 return "Default String";
10 }
11 }
12

  1 // Implement MyIF.
2 class MyIFImp implements MyIF {
3 // Only getNumber() defined by MyIF needs to be implemented.
4 // getString() can be allowed to default.
5 public int getNumber() {
6 return 100;
7 }
8 }
9

  1 // Use the default method.
2 class DefaultMethodDemo {
3 public static void main(String args[]) {
4
5 MyIFImp obj = new MyIFImp();
6
7 // Can call getNumber(), because it is explicitly
8 // implemented by MyIFImp:
9 System.out.println(obj.getNumber());
10
11 // Can also call getString(), because of default
12 // implementation:
13 System.out.println(obj.getString());
14 }
15 }
16

  1 class MyIFImp2 implements MyIF {
2 // Here, implementations for both getNumber( ) and getString( ) are provided.
3 public int getNumber() {
4 return 100;
5 }
6
7 public String getString() {
8 return "This is a different string.";
9 }
10 }

9.5.2 一个更加实用的例子

  1 interface IntStack {
2 void push(int item); // store an item
3 int pop(); // retrieve an item
4
5 // Because clear( ) has a default, it need not be
6 // implemented by a preexisting class that uses IntStack.
7 default void clear() {
8 System.out.println("clear() not implemented.");
9 }
10 }

9.5.3 多级继承的问题

9.6 在接口中使用静态方法

  1 public interface MyIF {
2 // This is a "normal" interface method declaration.
3 // It does NOT define a default implementation.
4 int getNumber();
5
6 // This is a default method. Notice that it provides
7 // a default implementation.
8 default String getString() {
9 return "Default String";
10 }
11
12 // This is a static interface method.
13 static int getDefaultNumber() {
14 return 0;
15 }
16 }

9.7 关于包和接口的最后说明

学习笔记(二)--->《Java 8编程官方参考教程(第9版).pdf》:第七章到九章学习笔记的相关教程结束。

《学习笔记(二)--->《Java 8编程官方参考教程(第9版).pdf》:第七章到九章学习笔记.doc》

下载本文的Word格式文档,以方便收藏与打印。