Visibility Modifiers

Purpose:

To declare the visibility of a method or an instance variable.

Mechanics:

[public, protected, or private] <other modifiers> <return type> <method name>(<parameter list>) {
/* Java statements */
}

[public, protected, or private] <other modifiers> <data type> <variable name>;

Example:

public void myMethod() {
/* Java statements */
}

private int myNumber;

Usage:

  • public, protected, and private are possible modifiers that can appear anywhere in the space-separated list of modifiers.
  • A method which is declared public is visible to every object, including those outside of the package in which the class which contains the method is defined. Likewise, an instance variable declared public can be accessed and modified by any object. Subclasses inherit public methods and instance variables and have full access to them.
  • A protected method is accessible by any object in the same package, or by any subclass, regardless of package. A protected instance variable can also be accessed and modified by any object in the same package. Subclasses inherit protected instance variables and have full control over them, but cannot directly access the protected instance variables in instances of superclass type or another subclass type if those classes are defined in a different package.
  • A private method or instance variable is visible only to the object in which it is defined or declared. Subclasses do not inherit private methods or instance variables.

Restrictions:

  • A method or instance variable can only be declared one of public, protected, and private. A method or instance variable declared without any of these modifiers is considered "package-friendly" and is visible to and, in the case of variables, modifiable by any object in the package.
  • A method which is declared abstract cannot also be declared private.
  • It is generally considered poor style to declare an instance variable public.
Back to the Table of Contents
email suggestions to: cs015tas@cs.brown.edu