为什么我可以实例化这个抽象class?

Why can I instantiate this abstract class?

我试图理解 Java 中的抽象 classes 所以我在 IntelliJ 中编写了这个代码片段:

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

@Overrideread() 存根由 IntelliJ 自动创建。

既然InputStream是一个抽象class,为什么我可以用new关键字实例化它?


还有一件事。当我像这样删除方法存根时:

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

IDE 表示 InputStream 是抽象的,因此无法实例化(如预期的那样)。

那么,为什么前者有效而后者无效呢?

这个read()方法从何而来?

您没有在第一个示例中实例化 InputStream。您正在实例化一个扩展 InputStream 并实现 InputStream - read() 的唯一抽象方法的匿名 class。那个匿名class不是抽象的,所以你可以实例化它。

另一方面,new InputStream() 尝试实例化抽象 class,这是不可能的。