what is the difference in using InputStream instead of FileInputStream while creating the FileInputStream object

后端 未结 5 968
天涯浪人
天涯浪人 2021-02-02 13:54

This may be a silly one, but I want to know the background operation difference.

  1. InputStream is = new FileInputStream(filepath);
  2. FileIn
5条回答
  •  被撕碎了的回忆
    2021-02-02 14:27

    There is no real difference. FileInputStream extends InputStream, and so you can assign an InputStream object to be a FileInputStream object. In the end, it's the same object, so the same operations will happen.

    This behavior is called Polymorphism and is very important in Object-Oriented Programming.

    Your first line of code is probably more desirable than the second as it doesn't lock you into a FileInputStream.

    This is one of the strengths of object oriented programming. Not specifying a type allows you to change what type of stream you are using later on. If you are sure you'll only ever need a FileInputStream here, use the second line of code.

提交回复
热议问题