javaoopinterface

Why Java interface inner class protected method is accessible from outside?


I have following code:

public interface ISomeInterface {

   class A {
      protected static void protectedMethod() {
         System.out.println("protectedMethod");
      }
      private static void privateMethod() {
         System.out.println("privateMethod");
      }

   }
}

In main, I can call protectedMethod but not privateMethod. Why is that?

public class Main {
   public static void main(String[] args) {

      ISomeInterface.A.protectedMethod(); //okay!
      //ISomeInterface.A.privateMethod(); // Compilation error
   }
}   

Solution

  • As per documentation:

    The protected keyword in Java is an access modifier used for member variables and methods. It provides a level of access control that allows access within the same package and by subclasses, even if they are in different packages.