Class 实现一个从 autcloseable 扩展的接口
Class implementing an interface that extends from autcloseable
我有一个 class 实现了一个从 autocloseable 扩展而来的接口。我的疑问是,只有来自我的界面的方法可以自动关闭,或者来自我的 class(而不是来自界面)的方法也可以自动关闭?
您误解了 AutoCloseable
的目的:它不是按方法,而是按对象或按资源持有者:
try (YourAutoCloseable aut = new YourAutoCloseable(...)) {
...
} // close is called somewhere after this '}'
这更像是一个编译器接口,允许您的对象在 try-with-resource 中用作资源。这并不意味着您必须在 try-with-resource 中使用,而是您应该使用。
这就像 Iterable
对应 foreach
。
我想你可能对继承感到困惑。
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
接口只有一个方法void close()
,并且必须由任何直接声明implements AutoClosable
的class来实现。从 class 继承的每个 class 也是一个 AutoClosable
类型,并且自动具有一个已实现的 public close()
方法。
我有一个 class 实现了一个从 autocloseable 扩展而来的接口。我的疑问是,只有来自我的界面的方法可以自动关闭,或者来自我的 class(而不是来自界面)的方法也可以自动关闭?
您误解了 AutoCloseable
的目的:它不是按方法,而是按对象或按资源持有者:
try (YourAutoCloseable aut = new YourAutoCloseable(...)) {
...
} // close is called somewhere after this '}'
这更像是一个编译器接口,允许您的对象在 try-with-resource 中用作资源。这并不意味着您必须在 try-with-resource 中使用,而是您应该使用。
这就像 Iterable
对应 foreach
。
我想你可能对继承感到困惑。
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
接口只有一个方法void close()
,并且必须由任何直接声明implements AutoClosable
的class来实现。从 class 继承的每个 class 也是一个 AutoClosable
类型,并且自动具有一个已实现的 public close()
方法。