java - 实现从 autcloseable 扩展的接口(interface)的类

标签 java java-11

我有一个类,它实现了一个从 autocloseable 扩展的接口(interface)。我的疑问是,只有我的接口(interface)中的方法可以自动关闭,或者我的类(而不是接口(interface))中的方法也可以自动关闭?

最佳答案

我认为您可能对继承感到困惑。

interface MyInterface{
  void method();
}

class Super implements MyInterface{
  /* must be implemented. If it's not, then it would NOT also be a MyInterface type */
  public void method(){ ... }
}

class SubClass extends Super {
  // if nothing is added, then only the methods from Super will be a part of SubClass.
  // that means method() is part of this class.
  // It also implements MyInterface, because Super does.
}

所以你可以这样调用方法:

// SubClass is a SubClass type, a Super type and a MyInterface type
MyInterface test = new SubClass();  
test.method();

AutoCloseable 接口(interface)只有一个方法 void close(),并且必须由任何直接声明实现 AutoClosable 的类来实现。从该类继承的每个类也是 AutoClosable 类型,并且自动具有实现的 public close() 方法。

关于java - 实现从 autcloseable 扩展的接口(interface)的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59848164/

相关文章:

java - 什么是删除——删除对泛型有哪 4 个限制?

java - 依赖冲突并且找不到 jar 来解决该问题

java - 如何配置java在jdk 9、10和11中应使用的DNS服务器

java - JasperReports 打印空 PDF

java - Hibernate @Version 不适用于一对多

java - 如何使用 webflux Webclient 创建带参数的请求?

java - 错误 -> cucumber.runtime.CucumberException : Failed to instantiate class <class> - this class doesn't have an empty or a page enabled constructor"

java - 是否有一种功能方法可以遍历基于最后处理的项目进行累积和过滤的流?

java - 无法使用 Java 11 运行 JOOQ GenerationTool(NoClassDefFoundError : javax/xml/bind/annotation/XmlSchema)

java - 登录 JDK11 HttpClient