为什么接口是静态的? [英] Why are interfaces static?

查看:126
本文介绍了为什么接口是静态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我的内部类中没有接口?为什么它们本身就是 static ?对不起,如果这是一个愚蠢的问题,我已经尽力一次又一次谷歌,但我似乎无法将它包裹在我的头脑中。为什么我不能在内部类/本地类中声明这些?

Why can I not have a interface inside of a inner class? Why are they inherently static? Sorry if it's a stupid question, I've tried my best to google this again and again but I can't seem to wrap it around my head. As in why cannot I declare these in inner classes/local classes?

同样作为确认,我们可以在接口中拥有静态最终变量的原因是因为它们没有指定状态或任何类型的实现权限?如果我们丢失 static 并且仅使用final,我们需要一个没有意义的实例,因为你无法实例化一个接口。对不起,我真的很困惑,我知道我应该提出另一个问题,但我认为这两个问题有些相关。

Also just as a confirmation, the reason we can have static final variables in a interface is because they do not specify the state or any of that sort of the implementation right? If we lose static and use just a final, we need a instance which makes no sense cause you can't instantiate a interface. Sorry, I really am confused, and I know I should just make another question but I think these two questions are somewhat related.

推荐答案

想想 static 的含义 - 与特定实例无关。因此,正如您所指出的,类 Foo static 字段是一个不属于任何<$的字段c $ c> Foo 实例,而是属于 Foo 本身。

Think about what static means - "not related to a particular instance". So, as you point out, a static field of class Foo is a field that does not belong to any Foo instance, but rather belongs to the Foo class itself.

现在想想接口是什么 - 它是一个契约,一个实现它的类承诺提供的方法列表。另一种思考方式是接口是一组与特定类无关的方法 - 任何类都可以实现它,只要它提供这些方法即可。

Now think about what an interface is - it's a contract, a list of methods that classes which implement it promise to provide. Another way of thinking about this is that an interface is a set of methods that is "not related to a particular class" - any class can implement it, as long as it provides those methods.

因此,如果某个接口与任何特定类无关,那么显然一个接口与某个类的实例无关 - 对吗?

So, if an interface is not related to any particular class, clearly one could not be related to an instance of a class - right?

*注意,正如@Owlstead所指出的,有一些方法可以在类中定义接口。但是,为了绕过界面(这似乎是你正在处理的东西)包裹你的头脑,我现在会忽略这些可能性,因为它们会分散注意力,并且可能会模糊界面的目的。

*Note, as @Owlstead points out, there are ways of defining interfaces within classes. But, for the purposes of wrapping your head around what an interface is (which seems to be what you're working on), I would ignore those possibilities for now as they distract from and possibly obscure the purpose of interfaces in general.

这篇关于为什么接口是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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