Search code examples
javaaccess-modifiers

Did Java's default access modifier used to be public


Back in 2004, when I took an intro to CS course at RIT, my professor stressed really hard about us remembering to put in access modifiers. Without it, the default access would be public, is what I remember the professor saying. Maybe my memory is wrong, and the professor didn't actually say it, but clearly that isn't the case now. I am wondering if that used to be the case at some point though and maybe Sun changed it at some point post-2004?


Solution

  • Java classes without access modifiers have been package-private since Java 1.0.

    Here is a link to the applicable section of the JLS 1.0:

    If a class or interface type is declared public, then it may be accessed by any Java code that can access the package in which it is declared. If a class or interface type is not declared public, then it may be accessed only from within the package in which it is declared.

    For members inside types, it says:

    A member (field or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:

    • If the member or constructor is declared public, then access is permitted. All members of interfaces are implicitly public.
    • Otherwise, if the member or constructor is declared protected, then access is permitted only when one of the following is true:

      • Access to the member or constructor occurs from within the package containing the class in which the protected member is declared.
      • Access occurs within a subclass of the class in which the protected member is declared, and the access is correct as described in §6.6.2.
    • Otherwise, if the member or constructor is declared private, then access is permitted only when it occurs from within the class in which it is declared.

    • Otherwise, we say there is default access, which is permitted only when the access occurs from within the package in which the type is declared.

    Which means that if left without a modifier, a member/constructor of a class would be package-private, not public.

    Members of interfaces, though, are never anything other than public, so applying access modifiers to them won't change a thing (well, if you try private or protected you'll get a compilation error), so whatever the you remember the professor saying, it doesn't apply to interfaces.