JVM Knowledge

In this section:

  • Let D be the class containing the method invocation.
  • Let Q be the qualifying class or interface 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 class or interface Q is accessible:

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

If Q is protected, it is necessarily a nested class or interface, so at compile time, its accessibility is affected by the accessibility of classes and interfaces enclosing its declaration. However, during linkage, its accessibility is not affected by the accessibility of classes and interfaces enclosing its declaration. Moreover, during linkage, a protected Q is as accessible as a public Q. 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 Q or a superclass or superinterface of Q. 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 class or interface 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 subclass of C or C itself; and (ii) if m is a protected instance method, then Q must be a subclass of D or D itself.

    This is the only place where Q is involved in checks for m, because a protected instance method may only be invoked via a qualifying class or interface 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 class or interface.

If either Q 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 class still implements the specified interface. If the target reference class does not still implement the interface, then an IncompatibleClassChangeError occurs.