我是新來的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'的值 - 但我們不知道確切的類型,因爲它可能是平臺依賴的。有關其他示例,請參閱「集合」框架。 –