为什么可以将变量分配给接口类型? [英] Why can variables be assigned to interface type?

查看:79
本文介绍了为什么可以将变量分配给接口类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手,正在尝试学习接口的概念.我在网上看到下面的代码.我知道该接口无法实例化.我的问题是,WatchService,Path,WatchKey和WatchEvent都是接口,如何将变量分配给接口类型?和实例化一样吗?

I'm new to Java and am trying to learn the concept of interface. I saw the code below online. I understand that interface can't be instantiated. My question is, WatchService, Path, WatchKey and WatchEvent are all interface, how come variables can be assigned to interface type? Is is the same as instantiation?

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);
            }
        } 
    }
}

推荐答案

我将举例说明.

假设我要您带我一个 sphere .然后,您给我带来一个沙滩球.

Suppose that I ask you to bring me a sphere. You then bring me a beach ball.

一个球体不存在,它是一个概念,一个几何对象,一个沙滩球是一个可以视为球体的物质对象.

A sphere doesn't exist, it's a concept, a geometrical object and a beach ball is a material object which can be considered a sphere.

几乎是同一件事,interface通过其公开的界面(可以在假装为implement的对象上调用的方法)定义对象的特征,但它本身并不是实质性的对象

That's approximately the same thing, an interface defines the characteristics of an object through its exposed interface (the methods that can be called on an object which pretend to implement that interface) but it's not a material object per se.

因此,即使该球不存在,我也可以将沙滩球视为一个球.实例化一个球体没有任何意义,因为无法实例化一个球体,但是我可以将沙滩球视为一个球体.

So I can consider a beach ball as a sphere even if the sphere doesn't exist. It doesn't make any sense to instantiate a sphere, since a sphere can't be instantiated, but I can treat a beach ball as a sphere.

这篇关于为什么可以将变量分配给接口类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆