作为 SeekableByteChannel是一个接口(interface),我们如何从Files类的newByteChannel调用它的方法方法。
我知道如何调用它。但我无法理解这个概念,因为接口(interface)没有实现该行为
还有一个问题。我在java示例代码中多次看到调用或调用接口(interface)方法。但据我所知,接口(interface)没有初始化或实现这些方法。
SeekableByteChannel idd = Files.newByteChannel(file);
idd.size();
上面的代码是如何工作的,因为SeekableByteChannel是一个接口(interface),Files类没有实现SeekableByteChannel的方法。所以SeekableByteChannels方法是在哪里初始化的。
请帮忙
最佳答案
Java 中的接口(interface)
只不过是一个契约;在编译器级别,唯一的约定是,如果您实现
接口(interface),则必须实现所有方法(对于非抽象
的类):
public interface Foo
{
/*
* Any invocation of this method sends the instance to the moon
*/
void foo();
}
如果您有一个可以实例化并实现 Foo
的具体类,例如:
public class MyClass
implements Foo
{
// must implement foo()
@Override
public void foo() { stayOnEarth(); }
}
那么你可以这样做:
final Foo foo = new MyClass();
当您引用 Foo
类型的实例时,这意味着您可以在其上调用 foo()
:
foo.foo();
JVM 将查找方法 foo()
并找到它。
现在:您已经实现了 foo()
的事实是一回事;您遵守此接口(interface)的契约的事实是另一回事。如果您留在地球上或直接前往心宿二,编译器不会发出
这首先是一个信任问题:如果你实现一个接口(interface),你应该理解这个接口(interface)的含义;这就是为什么有文档。编译器无法提供更多帮助,只能强制您至少实现所需的方法。
关于java - SeekableByteChannel 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17073855/