Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default access modifier for interface methods in Java 9?

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?

like image 320
Alok Avatar asked Aug 08 '17 17:08

Alok


2 Answers

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.

like image 157
Nicolai Parlog Avatar answered Oct 06 '22 00:10

Nicolai Parlog


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

like image 22
Seabass Avatar answered Oct 05 '22 23:10

Seabass