【发布时间】:2016-02-11 23:39:59
【问题描述】:
我是 Java 新手,正在尝试学习接口的概念。我在网上看到了下面的代码。我知道该接口无法实例化。我的问题是,WatchService、Path、WatchKey 和 WatchEvent 都是接口,为什么变量可以分配给接口类型?和实例化一样吗?
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class WatchServices {
public static void main(String[] args) throws IOException {
WatchService ws1 = FileSystems.getDefault().newWatchService();
Path p1 = Paths.get("/Users/justin/Desktop/Codes Netbean/JavaRandom");
WatchKey wk1 = p1.register(ws1, ENTRY_CREATE);
while(true){
for(WatchEvent<?> event : wk1.pollEvents()){
System.out.println(event.kind());
Path file = (Path)event.context();
System.out.println(file);
}
}
}
}
【问题讨论】:
-
您将编译时类型与运行时类型混淆了。声明一个变量定义了它的编译时类型——在运行时,任何兼容的引用都可以分配给它。
interface指定引用的对象必须满足的 contact。所以WatchService是interface,我们知道在运行时FileSystems.newWatchService()将返回一些实现interface的值——但我们不知道确切的类型,因为这很可能取决于平台。有关其他示例,请参阅Collection框架。
标签: java interface instantiation