JVM Knowledge

In this section:

  • Let D be the class containing the method invocation.
  • Let T be the qualifying type of the method invocation (§13.1).
  • Let m be the name of the method as determined at compile time (§15.12.3).

An implementation of the Java programming language must ensure, as part of linkage, that the type T is accessible:

  • If T is in the same package as D, then T is accessible.
  • If T is in a different package than D, and their packages are in the same module, and T is public or protected, then T is accessible.
  • If T is in a different package than D, and their packages are in different modules, and T's module exports T's package to D's module, and T is public or protected, then T is accessible.

If T is protected, it is necessarily a nested type, so at compile time, its accessibility is affected by the accessibility of types enclosing its declaration. However, during linkage, its accessibility is not affected by the accessibility of types enclosing its declaration. Moreover, during linkage, a protected T is as accessible as a public T. These discrepancies between access control at compile time (§6.6) and access control at run time are due to limitations in the Java Virtual Machine.

The implementation must also ensure, during linkage, that the method m can still be found in T or a supertype of T. If m cannot be found, then a NoSuchMethodError (which is a subclass of IncompatibleClassChangeError) occurs. If m can be found, then let C be the type that declares m. The implementation must ensure, during linkage, that the declaration of m in C is accessible to D:

  • If m is public, then m is accessible.

  • If m is protected, then m is accessible iff (i) either D is in the same package as C, or D is a subtype of C or C itself; and (ii) if m is a protected instance method, then T must be a subtype of D or D itself.

    This is the only place where T is involved in checks for m, because a protected instance method may only be invoked via a qualifying type that aligns with the invoker's type.

  • If m has package access, then m is accessible iff D is in the same package as C.

  • If m is private, then m is accessible iff D is C, or D encloses C, or C encloses D, or C and D are both enclosed by a third type.

If either T or m is not accessible, then an IllegalAccessError occurs (§12.3).

If the invocation mode is interface, then the implementation must check that the target reference type still implements the specified interface. If the target reference type does not still implement the interface, then an IncompatibleClassChangeError occurs.