Default access modifier for interface methods in Java 9?
Asked Answered
S

3

8

Java 9 allows us to have private methods in interface, which means that not explicitly marking public methods is no longer superfluous.

However, is it now mandatory to do so? I hope the specification still assumes public abstract as the default modifier for methods to maintain backward compatibility with earlier source code?

Selfknowledge answered 8/8, 2017 at 17:6 Comment(0)
B
15

The Java 9 Language Specification says in §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.

Unfortunately, I can't find a link that does not lead to a PDF, diffing the old and new JLS.

Beagle answered 8/8, 2017 at 19:4 Comment(0)
M
2

What I was taught:

All members in an Interface are implicitly public and cannot be declared with any other access modifier, unless specified below:

  • Fields & all variables are public static final implicitly
  • method signatures, default methods, (permitted as of Java 8) declared with the 'default' modifier.
  • Static methods (permitted as of Java 8)
  • Private methods (permitted as of Java 9) both static and non-static concrete methods can be private.
  • Nested types.
  • Method bodies exist only for default, private and static methods.

Source: Tim Buschalka's Learn Programming Academy

Also a very clear but somewhat long explanation: https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

Miltonmilty answered 24/3, 2021 at 12:11 Comment(0)
R
0

Java 9v onwards : Inside interface

  1. Private static methods and
  2. Private non static methods are allowed.

Example:

interface Example{

  private static void m1(){}

  private void m2(){}

  private void m3(){}

}
Rockrose answered 24/6, 2024 at 14:23 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.