接口中的变量 [英] Variables in Interface

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

问题描述

为什么接口中使用的变量是PUBLIC STATIC FINAL?为什么特别是静态?

Why is that a variable used in an Interface is PUBLIC STATIC FINAL? Why "static" in particular?

推荐答案

在接口中声明的字段无论如何都只能是一个常量,所以它为什么要依赖您使用哪个实例来访问它?

A field declared in an interface can only be a constant anyway, so why would it depend on which instance you use to access it?

现在将字段放在接口中的风格往往很差。该接口旨在反映实现它的类的功能 - 这与常量的概念完全正交。使用接口只是来声明一堆常量当然是一个令人讨厌的想法。我偶尔会发现使接口类型暴露出简单实现的常量很有用 - 例如,过滤接口可能有ALLOW_ALL和ALLOW_NONE字段。

Putting fields in interfaces is often poor style anyway these days. The interface is meant to reflect the capabilities of classes that implement it - which is completely orthogonal to the idea of a constant. It's certainly a nasty idea to use an interface just to declare a bunch of constants. I do occasionally find it useful to make the interface type expose constants which are simple implementations - so a filtering interface might have "ALLOW_ALL" and "ALLOW_NONE" fields, for example.

我想你可以设想实现一个接口 实际上为你的类添加一个实例字段的场景 - 但这会破坏封装,不仅仅是隐含的public,但也可以通过指定部分实现而不是API。

I suppose you could conceive of a scenario where implementing an interface did actually add an instance field to your class - but that would break encapsulation not only in terms of it being implicitly public, but also by specifying part of the implementation instead of the API.

这篇关于接口中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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