4

The classes java.io.Reader and java.io.InputStreamReader both have read methods with the exact same signature

public int read(char[] charbuf, int offset, int length) throws IOException

Now according to the java documentation the class java.io.FileReader inherits both these read() methods from both the above-mentioned classes.

Now as FileReader extends InputStreamReader which further extends Reader

(Reader <-- Inputstreamreader <-- FileReader)

and the read() has same signature in both classes, shouldn't it have been that InputStreamReader overrode the read() from Reader and FileReader inherited that over-ridden method?? Or am i missing something here??

Also the two read()s inherited by FileReader have slightly different functionality (something about one blocks while waiting for input while the other doesn't).

Surender Thakran
  • 3,958
  • 11
  • 47
  • 81
  • The docs don't say "it inherits both", it just lists the methods that are inherited from superclasses, by superclass. It doesn't go in and remove inherited methods from classes "higher up" in the inheritance chain. – Dave Newton May 14 '12 at 10:10

2 Answers2

4

The method in InputStreamReader provides the implementation for the abstract method in Reader. FileReader doesn't override that method any further; it just inherits the implementation from InputStreamReader.

Note that there are four signatures for read:

public int read()
public int read(char[] cbuf, int offset, int length)
public int read(char[] cbuf)
public int read(CharBuffer target)

InputStreamReader only overrides the first two of these. Perhaps that's what was confusing you?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

Well let's check the source code shall we?

Class Reader:

abstract public int read(char[] cbuf,
    int off,
    int len) throws IOException

So, abstract, nothing to see here.

Class InputStreamReader:

public int read(char[] cbuf,
    int offset,
    int length) throws IOException 

{
        return sd.read(cbuf, offset, length);
}

So here we have an override of the method from Reader.

Finally, FileReader has no such method defined, so it simply inherits it from InputStreamReader.

Tudor
  • 61,523
  • 12
  • 102
  • 142