我是新来的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'的值 - 但我们不知道确切的类型,因为它可能是平台依赖的。有关其他示例,请参阅“集合”框架。 –