javainterfacejava-9method-modifier

Java 9 Interface : Why default Modifier Converted into public Modifier


My Question is about interface. I create an interface and define four methods: first method is a private method; second is a default method; third is a static method; and fourth is an abstract method.
After compiling this interface and checking its profile: the default method is converted into a public method, and both the static and abstract methods have a prepended public modifier. Why is this?

Code:

 interface InterfaceProfile {

    private void privateM() {   //this method is hidden
        System.out.println("private Method");
    }

    default void defaultM() {
        System.out.println("Default Method");
    }

    static void staticM() {
        System.out.println("Static Method");
    }

    void doStuff(); //by default adds the public modifier
}

InterfaceProfile class

    D:\Linux\IDE\Workspace\OCA-Wrokspace\Ocaexam\src>javap mods\com\doubt\session\InterfaceProfile.class
Compiled from "InterfaceProfile.java"
interface com.doubt.session.InterfaceProfile {
  public void defaultM();
  public static void staticM();
  public abstract void doStuff();
}

Solution

  • Simple: by default, all methods in an interface are public. You can restrict that by applying private, but whenever you do not do that, that default kicks in. Thus: there is no conversion taking place at all.

    Quoting the Java Language Specification:

    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.

    ( the ability to have private methods in interfaces was introduced with Java 9, as people discovered that Java 8 default methods often created the need to have, well, private methods that such default methods could make use of, without making these helper methods publicly visible )