Java: Rules for accessing members

This entry is part 46 of 54 in the series Learn Java

These access rules apply to members of a class:

  • All the fields and methods of a class can always be used within the body of the class itself.
  • If a member of a class is declared with the public modifier, it means that the member is accessible anywhere the containing class is accessible. This is the least restrictive type of access control.
  • If a member of a class is declared private, the member is never accessible, except within the class itself. This is the most restrictive type of access control.
  • If a member of a class is declared protected, it is accessible to all classes within the package.
  • If a member of a class is not declared with any of these modifiers, it has default access and it is accessible to code within all classes that are defined in the same package but inaccessible outside of the package.

In the example below, we have the members all set at private.  This is the most restrictive of them all.

package javaapplication40;

public class Music {

    private String artiste;
    private String rockband;

    private void live() {
        this.artiste = "Lady Gaga";
        System.out.println(artiste);
    }

    private void record() {
        this.rockband = "Nirvana";
        System.err.println(rockband);
    }

    public static void main(String[] args) {

        Music m = new Music();
        m.live();
        m.record();

    }
}

members

Series Navigation<< Java: Access to classes and members
Java: Abstract class >>