Java:接口可以包含在其中定义的常量变量吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4012124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:22:20  来源:igfitidea点击:

Java: Can interfaces contain constant variables defined in them?

javainterfaceconstants

提问by kiki

Can I can create public static finalvariables in an interface? Can I keep some common constant values defined in these files?

我可以public static final在接口中创建变量吗?我可以保留在这些文件中定义的一些通用常量值吗?

回答by Jon Skeet

Yes, you can:

是的你可以:

public interface Constants
{
    public static final int ZERO = 0;
}

However, it's generallyreckoned not to be a good idea these days. It's not so bad if the interface has a real purpose as well, and the constants are likely to be used by most of the implementations... but introducing an interface justto make it easier to get to constants is an abuse of the purpose of interfaces, really. (And that's what used to happen a lot.)

然而,现在人们普遍认为这不是一个好主意。这不是那么糟糕,如果接口有一个现实目标,以及和常数都可能被大多数实现使用......但引入接口只是使它更容易得到常数是目的的滥用接口,真的。(这就是过去经常发生的事情。)

回答by Kel

Yes, you can keep constants in interfaces. BTW, it's considered to be not very good practice.

是的,您可以在接口中保持常量。顺便说一句,这被认为不是很好的做法。

回答by kuriouscoder

Certainly, publicconstants can be used declared inside interfaces. One thing, however, if your interface is just going to be placeholders for constants, use enuminstead

当然,public可以在接口内部声明使用常量。但是,有一件事,如果您的界面只是作为常量的占位符,请enum改用