代码之家  ›  专栏  ›  技术社区  ›  artificialidiot

有什么好的例子来了解语言的OO特性和构造?

oop
  •  0
  • artificialidiot  · 技术社区  · 16 年前

    短的 以及一些很好的例子来演示一种语言的OO特性,作为对其他程序员的介绍。所谓“好”,我的意思是,它们可以运行并输出一些有意义的东西,而不是foobar的东西。

    1 回复  |  直到 16 年前
        1
  •  1
  •   joev    16 年前

    一个很容易理解的“真实世界”例子是java.io.InputStream班级和孩子们。这是多态性的一个很好的例子:如果您编写代码来理解如何使用InputStream,那么底层类如何工作并不重要,只要它符合InputStream强加的契约。所以,你可以在某个类中有一个方法

    public void dump(InputStream in) throws IOException {
      int b;
      while((b = in.read()) >= 0) {
        System.out.println(b);
      }
    }
    

    此方法不关心数据来自何处。

    现在,如果要对文件中的数据使用dump方法,可以调用

    dump(new FileInputStream("file"));
    

    或者,如果要对来自套接字的数据使用dump,

    dump(socket.getInputStream());
    

    dump(new ByteArrayInputStream(theArray));
    

    dump(new SequenceInputStream(new FileInputStream("file1"), 
                                 new FileInputStream("file2"));
    

    public class ZerosInputStream extends InputStream {
      protected int howManyZeros;
      protected int index = 0;
      public ZerosInputStream(int howManyZeros) {
          this.howManyZeros = howManyZeros;
      }
    
      @Override
      public int read() throws IOException {
        if(index < howManyZeros) {
            index++;
            return 0;
        } else {
            return -1;
        }
      }
    

    然后你可以使用 那个 在你的垃圾电话中:

     dump(new ZerosInputStream(500));