Java 接口中的方法是否应该使用或不使用 public 访问修饰符来声明?

发布于 2024-07-07 06:59:57 字数 281 浏览 7 评论 0原文

Java 接口中的方法应该使用还是不使用 public 访问修饰符来声明?

当然,从技术上讲,这并不重要。 实现接口的类方法始终是public。 但什么是更好的约定呢?

Java本身在这一点上并不一致。 例如,请参阅 CollectionComparable,或 FutureScriptEngine

Should methods in a Java interface be declared with or without the public access modifier?

Technically it doesn't matter, of course. A class method that implements an interface is always public. But what is a better convention?

Java itself is not consistent in this. See for instance Collection vs. Comparable, or Future vs. ScriptEngine.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

两仪 2024-07-14 06:59:57

JLS 明确了这一点:

允许为接口中声明的方法冗余地指定 public 和/或 abstract 修饰符,但出于风格问题,不鼓励这样做。

The JLS makes this clear:

It is permitted, but discouraged as a matter of style, to redundantly specify the public and/or abstract modifier for a method declared in an interface.

半山落雨半山空 2024-07-14 06:59:57

Java 接口中的 public 修饰符应该被省略(我认为)。

由于它没有添加任何额外的信息,它只是将注意力从重要的事情上转移开。

大多数样式指南会建议您将其忽略,但当然,最重要的是在整个代码库中保持一致,尤其是每个界面。 下面的例子很容易让那些 Java 不是 100% 流利的人感到困惑:

public interface Foo{
  public void MakeFoo();
  void PerformBar();
}

The public modifier should be omitted in Java interfaces (in my opinion).

Since it does not add any extra information, it just draws attention away from the important stuff.

Most style-guides will recommend that you leave it out, but of course, the most important thing is to be consistent across your codebase, and especially for each interface. The following example could easily confuse someone, who is not 100% fluent in Java:

public interface Foo{
  public void MakeFoo();
  void PerformBar();
}
み零 2024-07-14 06:59:57

随着 Java 8/9 中接口方法引入 privatestaticdefault 修饰符,事情变得更加复杂,我倾向于认为完整的声明更具可读性(需要 Java 9 来编译):

public interface MyInterface {

    //minimal
    int CONST00 = 0;
    void method00();
    static void method01() {}
    default void method02() {}
    private static void method03() {}
    private void method04() {}

    //full
    public static final int CONST10 = 0;
    public abstract void method10();
    public static void method11() {}
    public default void method12() {}
    private static void method13() {}
    private void method14() {}

}

With the introduction of private, static, default modifiers for interface methods in Java 8/9, things get more complicated and I tend to think that full declarations are more readable (needs Java 9 to compile):

public interface MyInterface {

    //minimal
    int CONST00 = 0;
    void method00();
    static void method01() {}
    default void method02() {}
    private static void method03() {}
    private void method04() {}

    //full
    public static final int CONST10 = 0;
    public abstract void method10();
    public static void method11() {}
    public default void method12() {}
    private static void method13() {}
    private void method14() {}

}
巴黎夜雨 2024-07-14 06:59:57

尽管这个问题很久以前就被问过,但我觉得全面的描述可以澄清为什么不需要在方法之前使用 public Abstract 和接口常量之前使用 public static final 。

首先,接口用于为一组不相关的类指定公共方法,每个类都有一个唯一的实现。 因此,不可能将访问修饰符指定为私有,因为它不能被其他要覆盖的类访问。

其次,虽然可以启动接口类型的对象,但接口是由实现它的类实现的,而不是继承的。 并且由于接口可能由不在同一包中的不同不相关类实现(实现),因此 protected 访问修饰符也无效。 因此,对于访问修饰符,我们只剩下公共选择。

第三,接口没有任何数据实现,包括实例变量和方法。 如果有逻辑原因在接口中插入实现的方法或实例变量,那么它必须是继承层次结构中的超类而不是接口。 考虑到这一事实,由于接口中不能实现任何方法,因此接口中的所有方法都必须是抽象的。

第四,接口只能包含常量作为其数据成员,这意味着它们必须是最终常量,当然最终常量被声明为静态以仅保留它们的一个实例。 因此 static Final 也是接口常量的必备条件。

所以总而言之,尽管在接口的方法之前使用 public abstract 和 public static final 在接口常量之前是有效的,但由于没有其他选项,因此被认为是多余的并且不被使用。

Despite the fact that this question has been asked long time ago but I feel a comprehensive description would clarify why there is no need to use public abstract before methods and public static final before constants of an interface.

First of all Interfaces are used to specify common methods for a set of unrelated classes for which every class will have a unique implementation. Therefore it is not possible to specify the access modifier as private since it cannot be accessed by other classes to be overridden.

Second, Although one can initiate objects of an interface type but an interface is realized by the classes which implement it and not inherited. And since an interface might be implemented (realized) by different unrelated classes which are not in the same package therefore protected access modifier is not valid as well. So for the access modifier we are only left with public choice.

Third, an interface does not have any data implementation including the instance variables and methods. If there is logical reason to insert implemented methods or instance variables in an interface then it must be a superclass in an inheritance hierarchy and not an interface. Considering this fact, since no method can be implemented in an interface therefore all the methods in interface must be abstract.

Fourth, Interface can only include constant as its data members which means they must be final and of course final constants are declared as static to keep only one instance of them. Therefore static final also is a must for interface constants.

So in conclusion although using public abstract before methods and public static final before constants of an interface is valid but since there is no other options it is considered redundant and not used.

心凉 2024-07-14 06:59:57

我不同意流行的答案,即公开意味着还有其他选择,所以它不应该在那里。 事实上,现在有了 Java 9 及更高版本,还有其他选择。

我认为 Java 应该强制/要求指定“public”。 为什么? 因为缺少修饰符意味着在其他任何地方都可以进行“包”访问,而将其作为特殊情况会导致混乱。 如果您只是用一条明确的消息(例如“接口中不允许包访问”)将其设置为编译错误,我们将消除由于选择省略“public”而引入的明显歧义。

请注意当前的措辞:https:// /docs.oracle.com/javase/specs/jls/se9/html/jls-9.html#jls-9.4

“接口主体中的方法可以声明为public
私人(§6.6)。 如果没有给出访问修饰符,则该方法是隐式公共的。 这是允许的,但不鼓励这样做
style,冗余地指定方法的 public 修饰符
接口中的声明。”

看到现在允许“私有”。我认为最后一句应该从 JLS 中删除。不幸的是,“隐式公共”行为曾经被允许,因为现在可能为了向后兼容性而保留它并导致混乱:缺少访问修饰符意味着接口中的“公共”和其他地方的“包”。

I disagree with the popular answer, that having public implies that there are other options and so it shouldn't be there. The fact is that now with Java 9 and beyond there ARE other options.

I think instead Java should enforce/require 'public' to be specified. Why? Because the absence of a modifier means 'package' access everywhere else, and having this as a special case is what leads to the confusion. If you simply made it a compile error with a clear message (e.g. "Package access is not allowed in an interface.") we would get rid of the apparent ambiguity that having the option to leave out 'public' introduces.

Note the current wording at: https://docs.oracle.com/javase/specs/jls/se9/html/jls-9.html#jls-9.4

"A method in the body of an interface may be declared public or
private (§6.6). If no access modifier is given, the method is implicitly public. It is permitted, but discouraged as a matter of
style, to redundantly specify the public modifier for a method
declaration in an interface."

See that 'private' IS allowed now. I think that last sentence should have been removed from the JLS. It is unfortunate that the "implicitly public" behaviour was ever allowed as it will now likely remain for backward compatibilty and lead to the confusion that the absence of the access modifier means 'public' in interfaces and 'package' elsewhere.

鸠魁 2024-07-14 06:59:57

我总是写如果没有接口并且我正在编写直接实现时我会使用什么,即我会使用public

I always write what I would use if there was no interface and I was writing a direct implementation, i.e., I would use public.

十雾 2024-07-14 06:59:57

我会避免放置默认应用的修饰符。 正如所指出的,它可能会导致不一致和混乱。

我看到的最糟糕的是一个带有声明为抽象方法的接口...

I would avoid to put modifiers that are applied by default. As pointed out, it can lead to inconsistency and confusion.

The worst I saw is an interface with methods declared abstract...

随心而道 2024-07-14 06:59:57

我使用带有 public 修饰符的声明方法,因为它使代码更具可读性,尤其是在语法突出显示时。 不过,在我们最新的项目中,我们使用了 Checkstyle,它会在接口方法上的 public 修饰符的默认配置中显示警告,因此我改为忽略它们。

所以我不太确定什么是最好的,但我真正不喜欢的一件事是在接口方法上使用 public Abstract 。 Eclipse 有时在使用“Extract Interface”进行重构时会这样做。

I used declare methods with the public modifier, because it makes the code more readable, especially with syntax highlighting. In our latest project though, we used Checkstyle which shows a warning with the default configuration for public modifiers on interface methods, so I switched to ommitting them.

So I'm not really sure what's best, but one thing I really don't like is using public abstract on interface methods. Eclipse does this sometimes when refactoring with "Extract Interface".

我纯我任性 2024-07-14 06:59:57

接口中的方法默认是公共和抽象的原因对我来说似乎非常合乎逻辑且显而易见。

接口中的方法默认是抽象的,以强制实现类提供实现,并且默认情况下是公共的,因此实现类可以访问这样做。

在代码中添加这些修饰符是多余且无用的,只会导致您缺乏 Java 基础知识和/或理解的结论。

The reason for methods in interfaces being by default public and abstract seems quite logical and obvious to me.

A method in an interface it is by default abstract to force the implementing class to provide an implementation and is public by default so the implementing class has access to do so.

Adding those modifiers in your code is redundant and useless and can only lead to the conclusion that you lack knowledge and/or understanding of Java fundamentals.

娇妻 2024-07-14 06:59:57

我更喜欢跳过它,我在某处读到接口默认是 publicabstract

令我惊讶的是,这本书 - Head First Design Patterns 正在使用 public< /code> 带有接口声明和接口方法...这让我再次重新思考,我找到了这篇文章。

无论如何,我认为冗余信息应该被忽略。

I prefer skipping it, I read somewhere that interfaces are by default, public and abstract.

To my surprise the book - Head First Design Patterns, is using public with interface declaration and interface methods... that made me rethink once again and I landed up on this post.

Anyways, I think redundant information should be ignored.

⒈起吃苦の倖褔 2024-07-14 06:59:57

这完全是主观的。 我省略了多余的 public 修饰符,因为它看起来很混乱。 正如其他人所提到的 - 一致性是这个决定的关键。

有趣的是,C# 语言设计者决定强制执行这一点。 在 C# 中将接口方法声明为 public 实际上是一个编译错误。不过,跨语言的一致性可能并不重要,所以我猜这与 Java 并不直接相关。

It's totally subjective. I omit the redundant public modifier as it seems like clutter. As mentioned by others - consistency is the key to this decision.

It's interesting to note that the C# language designers decided to enforce this. Declaring an interface method as public in C# is actually a compile error. Consistency is probably not important across languages though, so I guess this is not really directly relevant to Java.

走走停停 2024-07-14 06:59:57

人们将通过 IDE 或 Javadoc 中的代码补全来了解您的界面,而不是通过阅读源代码。 因此,在源代码中添加“公开”是没有意义的——没有人阅读源代码。

People will learn your interface from code completion in their IDE or in Javadoc, not from reading the source. So there's no point in putting "public" in the source - nobody's reading the source.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文