Java Reference

Java Reference Home | Smart Soft Home

Variable Visibility

Two things determine variable visibility:

  1. Where the variable declared
  2. What visibility modifier is used

 ModifierDeclared whereExampleVisible to
local variablenoneWithin method bodyeThe method in which it is declared
method argumentnoneWithin a method's argument listd
private variableprivateWithin the class body but outside of any methodsaAll methods in the same class
package variablenonebAll methods in the same class + all methods in the same package (directory)
public variablepubliccAll methods in all packages everywhere
class MyClass{

  private int a;      //private variable
  int b;              //package variable
  public int c;       //public variable

  void meth1(int d){  //method argument
    int e;            //local variable
  }

}

In general, variables should be declared to be as invisible as possible.