abstract是声明抽象类和抽象方法的关键字

包含抽象方法的类叫抽象类,如果一个类中包含一个或多个抽象方法,该类必须被限定为抽象的,否则编译器会报错,抽象类不可创建对象,创建抽象类的对象编译器会报错

  1. //: interfaces/music4/Music4.java
  2. // Abstract classes and methods.
  3. package object;
  4. import static net.mindview.util.Print.print;
  5. enum Note {
  6. MIDDLE_C,MIDDLE_E,MIDDLE_F,
  7. }
  8. abstract class Instrument {
  9. private int i; // Storage allocated for each
  10. public abstract void play(Note n);
  11. public String what() { return "Instrument"; }
  12. public abstract void adjust();
  13. }
  14. class Wind extends Instrument {
  15. public void play(Note n) {
  16. print("Wind.play() " + n);
  17. }
  18. public String what() { return "Wind"; }
  19. public void adjust() {}
  20. }
  21. class Percussion extends Instrument {
  22. public void play(Note n) {
  23. print("Percussion.play() " + n);
  24. }
  25. public String what() { return "Percussion"; }
  26. public void adjust() {}
  27. }
  28. class Stringed extends Instrument {
  29. public void play(Note n) {
  30. print("Stringed.play() " + n);
  31. }
  32. public String what() { return "Stringed"; }
  33. public void adjust() {}
  34. }
  35. class Brass extends Wind {
  36. public void play(Note n) {
  37. print("Brass.play() " + n);
  38. }
  39. public void adjust() { print("Brass.adjust()"); }
  40. }
  41. class Woodwind extends Wind {
  42. public void play(Note n) {
  43. print("Woodwind.play() " + n);
  44. }
  45. public String what() { return "Woodwind"; }
  46. }
  47. public class Music4 {
  48. // Doesn\'t care about type, so new types
  49. // added to the system still work right:
  50. static void tune(Instrument i) {
  51. // ...
  52. i.play(Note.MIDDLE_C);
  53. }
  54. static void tuneAll(Instrument[] e)
  55. {
  56. for(Instrument i : e)
  57. tune(i);
  58. }
  59. public static void main(String[] args) {
  60. // Upcasting during addition to the array:
  61. Instrument[] orchestra = {
  62. new Wind(),
  63. new Percussion(),
  64. new Stringed(),
  65. new Brass(),
  66. new Woodwind()
  67. };
  68. tuneAll(orchestra);
  69. }
  70. } /* Output:
  71. Wind.play() MIDDLE_C
  72. Percussion.play() MIDDLE_C
  73. Stringed.play() MIDDLE_C
  74. Brass.play() MIDDLE_C
  75. Woodwind.play() MIDDLE_C
  76. *///:~

 

版权声明:本文为jiangfeilong原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/jiangfeilong/p/10204453.html