注:本文声明事项。

本博文整理者:刘军

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

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

7.1.1 重载构造函数

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

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

7.2 将对象用作参数

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

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

7.3 参数传递的深入分析

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

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

7.4 返回对象

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

7.5 递归

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


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

7.6 访问控制

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

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

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

7.7 理解st

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

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

7.8 final介绍

7.9 重新审视数组

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

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

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

7.10 嵌套类和内部类

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

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

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

7.11 String类介绍

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

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

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

7.12 使用命令行参数

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

7.13 varargs:可变长度参数

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

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

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

7.13.1 重载varargs方法

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

7.13.2 varargs方法与模糊性

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

第8章 继承

8.1 继承的基础知识

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

8.1.1 成员访问与继承

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

8.1.2 一个更实际的例子

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

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

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

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

8.2 使用super关键字

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

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

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

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

8.2.2 super的另一种用法

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

8.3 创建多级继承层次

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

8.4 构造函数的调用时机

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

8.5 方法重写

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

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

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

8.6 动态方法调度

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

8.6.1 重写方法的目的

8.6.2 应用方法重写

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

8.7 使用抽象类

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

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

8.8 在继承中使用final关键字

8.8.1 使用final关键字阻止重写

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

8.8.2 使用final关键字阻止继承

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

8.9 Object类

第9章 包和接口

9.1 包

9.1.1 定义包

9.1.2 包查找与CLASSPATH

9.1.3 一个简短的包示例

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

9.2 访问保护

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

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

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

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

9.3 导入包

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

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

9.4 接口

9.4.1 定义接口

9.4.2 实现接口

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

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

9.4.3 嵌套接口

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

9.4.4 应用接口

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

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

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

9.4.5 接口中的变量

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

9.4.6 接口可以扩展

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

9.5 默认接口方法

9.5.1 默认方法的基础知识

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

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

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

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

9.5.2 一个更加实用的例子

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

9.5.3 多级继承的问题

9.6 在接口中使用静态方法

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

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

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

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

    回到顶部 注:本文声明事项. 本博文整理者:刘军 本博文出自于: <Java8 编程官方参考教程>一书 声明:1:转载请标注出处.本文不得作为商业活动.若有违本之,则本人不负法律责任.违法 ...

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

    注:本文声明事项. 本博文整理者:刘军 本博文出自于: <Java8 编程官方参考教程>一书 声明:1:转载请标注出处.本文不得作为商业活动.违者本人不负法律责任.违法者自负一切法律责任. ...

  3. 学习笔记:java并发编程学习之初识Concurrent

    一.初识Concurrent 第一次看见concurrent的使用是在同事写的一个抽取系统代码里,当时这部分代码没有完成,有许多的问题,另一个同事接手了这部分代码的功能开发,由于他没有多线程开发的经验 ...

  4. Scala学习教程笔记二之函数式编程、Object对象、伴生对象、继承、Trait、

    1:Scala之函数式编程学习笔记: :Scala函数式编程学习: 1.1:Scala定义一个简单的类,包含field以及方法,创建类的对象,并且调用其方法: class User { private ...

  5. 【Todo】【读书笔记】Java多线程编程指南-设计模式篇

    下了这本书<Java多线程编程指南-设计模式篇>, 还有另一本<JAVA多线程设计模式>,据说内容有重复,结合着看.

  6. Java并发编程面试题 Top 50 整理版

    本文在 Java线程面试题 Top 50的基础上,对部分答案进行进行了整理和补充,问题答案主要来自<Java编程思想(第四版)>,<Java并发编程实战>和一些优秀的博客,当然 ...

  7. 学习笔记《Java多线程编程实战指南》二

    2.1线程属性 属性 属性类型及用途  只读属性  注意事项 编号(id) long型,标识不同线程  是  不适合用作唯一标识 名称(name) String型,区分不同线程  否  设置名称有助于 ...

  8. 学习笔记《Java多线程编程实战指南》三

    3.1串行.并发与并行 1.串行:一件事做完接着做下一件事. 2.并发:几件事情交替进行,统筹资源. 3.并行:几件事情同时进行,齐头并进,各自运行直到结束. 多线程编程的实质就是将任务处理方式由串行 ...

  9. 学习笔记《Java多线程编程实战指南》一

    1.1什么是多线程编程 多线程编程就是以线程为基本抽象单位的一种编程范式,和面向对象编程是可以相容的,事实上Java平台中的一个线程就是一个对象.多线程编程不是线程越多越好,就像“和尚挑水”的故事一样 ...

随机推荐

  1. JavaSE学习总结(九)—— Java访问数据库(JDBC)

    一.JDBC简介 JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java ...

  2. 设计模式---对象创建模式之工厂方法模式(Factory Method)

    前提:“对象创建”模式 通过“对象创建”模式绕开new,来避免对象创建(new)过程中所导致的紧耦合(依赖具体类),从而支持对象创建的稳定.它是接口抽象之后的第一步工作. 典型模式(表现最为突出) 工 ...

  3. python---基于memcache的自定义session类

    import config import hashlib import time import memcache import json conn = memcache.Client(["1 ...

  4. C和C++的区别和联系

    关于C和C++的区别是面试中经常会被问到的问题,本着即将面试的心态,进行知识整理,并对小知识点进行扩展: C/C++的联系: C++是C的超集,兼容大部分C的语法的结构: 联系嘛我只能想到这个,毕竟c ...

  5. Java POI 读取word文件

    Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能. 1.读取word 2003及word 2007需要 ...

  6. HDU - 1828 Picture

    题目链接 题意  多个矩形重叠在一起,求出轮廓线的长度. 分析  把矩形分成横线和竖线来处理.现在分析横线的,竖线同理.矩形的坐标都是整数,且范围不大,故此题不需要离散化.从下往上扫描横线,每遇到一条 ...

  7. Prim算法:最小生成树

    #define _CRT_SECURE_NO_WARNINGS /* 7 10 0 1 5 0 2 2 1 2 4 1 3 2 2 3 6 2 4 10 3 5 1 4 5 3 4 6 5 5 6 9 ...

  8. Ubuntu14.10安装TensorFlow1.0.1

    本文记录了在Ubuntu上安装TensorFlow的步骤.系统环境:Ubuntu14.10 64bitPython版本:Python 2.7.8TensorFlow版:TensorFlow 1.0.1 ...

  9. css颜色模式hsla和rgba

    在CSS3中可以使用RGBA和HSLA两种色彩模式,这两个都可以用来设置颜色以及指定透明度. rgba指的是:红色.绿色.蓝色.Alpha透明度(Red-Green-Blue-Alpha)前三个值取值 ...

  10. Js/Jquery 关闭 离开或刷新当前页面时提醒,和执行解绑取消提醒

    如图,现在的 cnblogs 或者QQ邮箱编辑页面,刷新.关闭提醒: <script src="../../Common/Js/jquery-1.8.1.min.js"> ...