1

I'm trying to understand abstract classes in Java so I wrote this code snippet in IntelliJ:

AutoCloseable ac = new BufferedInputStream(new InputStream() {
        @Override
        public int read() throws IOException {
            return 0;
        }
});

The @Override and read() stub was created automatically by IntelliJ.

Since InputStream is an abstract class, why can I instantiate it with the new keyword?


And another thing. When I delete the method stub like this:

AutoCloseable ac = new BufferedInputStream(new InputStream());

The IDE says that InputStream is abstract and therefore can't be instantiated (as expected).

So, why is the former valid and the latter not?

And where does this read() method come from?

de_dust
  • 291
  • 5
  • 13

1 Answers1

4

You are not instantiating InputStream in the first example. You are instantiating an anonymous class that extends InputStream and implements the only abstract method of InputStream - read(). That anonymous class is not abstract, so you can instantiate it.

On the other hand, new InputStream() attempts to instantiate an abstract class, which is not possible.

Eran
  • 387,369
  • 54
  • 702
  • 768