I tried compiling the following test interface:
public interface TestInterface {
void m();
abstract void am();
default void dm() { }
static void sm() { }
public void pm();
public abstract void pam();
public default void pdm() { }
public static void psm() { }
}
using the JDKs I happened to have lying around, namely: 8, 8u5, 8u11, 8u25, 8u40, and a jdk9-dev build from a couple days ago. It compiled successfully on all of these versions.
As others have noted, methods in an interface are all public, regardless of whether or not public
is specified. In addition, a method can either be abstract, default, or static, and a method is abstract if none of these is specified. (JLS 9.4) Finally, methods declared default
or static
must have a block { ... }
for the body, whereas abstract methods (whether declared or not) must have a semicolon ;
as the body. (JLS 9.4.3)
if the method is public I need to explicitly mention it as static too ... but why is this not enforced on default? (from comment) the keyword static needs to be there if it is public.
I don't see this. All interface methods are public, whether or not they explicitly declared as such. This is orthogonal to the method being static or default.
in fact specifying static with default gives an error.
Yes, a method can be static or default but not both.
I get an error "interface abstract methods cannot have body"
If you're getting this error, you must be specifying a block { ... }
as the body for an abstract method, regardless of whether or not the method is explicitly declared as abstract.
(JDK 9 has recently added support for private methods in interfaces.)