javaaccess-specifier

Difference between the default access specifier and protected access specifier in java


I was trying to learn java and when I went through access specifiers I had a doubt. What is the difference between the default one if none is specified and the protected access specifier in java?


Solution

  • The protected specifier allows access by all subclasses of the class in question, whatever package they reside in, as well as to other code in the same package. The default specifier allows access by other code in the same package, but not by code that is in subclasses residing in different packages. See Java Language Specification Section 6.6.

    EDIT: Per request of Michael Schmeißer (so others don't have to read through the comments or follow a link to find this): all members of interfaces are implicitly public. It is, in fact, a compile-time error to specify any access specifier for an interface member other than public (although no access specifier at all defaults to public access). Here's the full set of rules from the JLS for class members (see the above link for the rules for packages, top-level classes and interfaces, and arrays):

    A member (class, interface, 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 or constructor is declared.

    • Access is correct as described in §6.6.2. (This clause refers to the rules that allow derived classes to access protected members of superclasses; §6.6.2 starts: "A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object." It then elaborates on that.)

    • Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

    • 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.