What are the implicit specifier/modifiers of interface methods in Java 8?

前端 未结 3 572
逝去的感伤
逝去的感伤 2021-01-03 13:44

I understand that Interface methods are implicitly public. Java Docs Tutorial says

All abstract, default, and <

相关标签:
3条回答
  • 2021-01-03 14:34

    The language spec - specifically Section 9.4, states that abstract and public are implicit.

    Every method declaration in the body of an interface is implicitly public (§6.6). It is permitted, but discouraged as a matter of style, to redundantly specify the public modifier for a method declaration in an interface.

    An interface method lacking a default modifier or a static modifier is implicitly abstract, so its body is represented by a semicolon, not a block. It is permitted, but discouraged as a matter of style, to redundantly specify the abstract modifier for such a method declaration.

    This is why IntelliJ warns you about it; by the JLS, you're doing something completely redundant.

    As a bonus, fields in interfaces are implicitly public static final:

    Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.

    0 讨论(0)
  • 2021-01-03 14:35

    In Java 7, as well in Java 8, all fields defined in an interface are ALWAYS public, static, and final. Methods are public and abstract.

    Because your print() method does not have a body, it means that is an abstract method. With other words does not need to be declared explicitly abstract, that's why Intellij IDEA says is redundant.

    Methods without static or default are not implicitly abstract, even if it has a body. A non-abstract method with a body that is not default or static, cannot exist in an interface.

    0 讨论(0)
  • 2021-01-03 14:44

    Access modifiers

    In Java 8, we have as per Java Docs Tutorials,

    All abstract, default, and static methods in an interface are implicitly public, so you can omit the public modifier.

    Thus the only allowed access modifier in an Interface as of Java 8 is public. (Java 9 introduces private interface methods)

    public interface TestInterface {
        int print();//compiles and no IDE warning
        public int print1();//public redundant
    }
    

    Optional Specifiers

    abstract - methods in an interface that are not declared as default or static are implicitly abstract, so the abstract modifier is optional. But the method implementation must not be provided in such case.

    static- static needs to be explicitly specified and implementation provided.

    final - A final methods can't be overridden and is not allowed for an interface method.

    default - method can be explicitly declared default if the default implementation is provided.

    All fields in Interfaces are public, static and final.

    0 讨论(0)
提交回复
热议问题