• Java abstract 关键字


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

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

    //: interfaces/music4/Music4.java
    // Abstract classes and methods.
    package object;
    import static net.mindview.util.Print.print;
    
    
    enum Note {
        MIDDLE_C,MIDDLE_E,MIDDLE_F,
    }
    abstract class Instrument {
      private int i; // Storage allocated for each
      public abstract void play(Note n);
      public String what() { return "Instrument"; }
      public abstract void adjust();
    }
    
    class Wind extends Instrument {
      public void play(Note n) {
        print("Wind.play() " + n);
      }
      public String what() { return "Wind"; }
      public void adjust() {}
    }
    
    class Percussion extends Instrument {
      public void play(Note n) {
        print("Percussion.play() " + n);
      }
      public String what() { return "Percussion"; }
      public void adjust() {}
    }
    
    class Stringed extends Instrument {
      public void play(Note n) {
        print("Stringed.play() " + n);
      }
      public String what() { return "Stringed"; }
      public void adjust() {}
    }    
    
    class Brass extends Wind {
      public void play(Note n) {
        print("Brass.play() " + n);
      }
      public void adjust() { print("Brass.adjust()"); }
    }
    
    class Woodwind extends Wind {
      public void play(Note n) {
        print("Woodwind.play() " + n);
      }
      public String what() { return "Woodwind"; }
    }    
    
    public class Music4 {
      // Doesn't care about type, so new types
      // added to the system still work right:
      static void tune(Instrument i) {
        // ...
        i.play(Note.MIDDLE_C);
      }
      
      static void tuneAll(Instrument[] e) 
      {
        for(Instrument i : e)
          tune(i);
      }    
      public static void main(String[] args) {
        // Upcasting during addition to the array:
        Instrument[] orchestra = {
          new Wind(),
          new Percussion(),
          new Stringed(),
          new Brass(),
          new Woodwind()
        };
        tuneAll(orchestra);
      }
    } /* Output:
    Wind.play() MIDDLE_C
    Percussion.play() MIDDLE_C
    Stringed.play() MIDDLE_C
    Brass.play() MIDDLE_C
    Woodwind.play() MIDDLE_C
    *///:~
  • 相关阅读:
    解释 ASP.NET中的Web页面与其隐藏类之间的关系
    B/S与C/S的联系与区别
    三层架构
    列举 ASP.NET页面之间传递值的几种方式
    什么是SQL注入式攻击?如何防范?
    post、get的区别
    Session,ViewState,Application,cookie的区别?
    Vue 09.前后端交互
    Vue 08.webpack中使用.vue组件
    Vue 07.webpack
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/10204453.html
Copyright © 2020-2023  润新知