我有一个类,它实现了一个从 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/