Tho*_*hor 0 java interface instantiation
我是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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)