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,andprivateare possible modifiers that can appear anywhere in the space-separated list of modifiers.- A method which is declared
publicis visible to every object, including those outside of the package in which the class which contains the method is defined. Likewise, an instance variable declaredpubliccan be accessed and modified by any object. Subclasses inherit public methods and instance variables and have full access to them. - A
protectedmethod is accessible by any object in the same package, or by any subclass, regardless of package. Aprotectedinstance variable can also be accessed and modified by any object in the same package. Subclasses inheritprotectedinstance variables and have full control over them, but cannot directly access theprotectedinstance variables in instances of superclass type or another subclass type if those classes are defined in a different package. - A
privatemethod 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,andprivate. 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.
email suggestions to: cs015tas@cs.brown.edu
