zoukankan      html  css  js  c++  java
  • Java 抽象类和抽象方法

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

    如果从一个抽象类继承,并想创建该新类的对象,那么必须为基类中的所有抽象方法提供方法定义,如果不这样做(可以选择不做),那么导出类便也是抽象类,且编译器会强制我们用abstract关键字来限定这个类..

    可以创建没有任何抽象方法的抽象类,创建抽象类和抽象方法非常有用,因为我们可以使类的抽象性明确起来,并告诉用户和编译器打算怎么去使用它们,抽象类还是很有用的重构工具,因为它们使得我们可以很容易地将公共方法沿着继承层次结构向上移动

    抽象类的抽象方法,必须在导出类复写,抽象类的普通public方法,可以被导出类使用

    //: 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
    *///:~
  • 相关阅读:
    字符串
    Flume集群搭建
    hbase测试搭建
    hadoop2.0测试环境安装
    kafka集群报错
    kafka集群安装
    hadoop环境配置
    zookeeper安装
    虚拟机时间同步14 Aug 04:09:18 ntpdate[2941]: no server suitable for synchronization found
    python numpy中数组.min()
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/10204713.html
Copyright © 2011-2022 走看看