How the variables can be accessed by the rest of the program, depends on where the variable is declared and which access modifier is used. There are 2 kinds of variables - class variables and block variables. The area, where the variables can be accessed, is called as the scope of variables.
Class Variables -
Class variables are the variables declared with the class definition and are not part of any method. There are 3 access modifiers for class variables - public, private and protected. We have already discussed these access modifiers in previous posts - Encapsulation and Inheritance. Let's review the definition of three access modifiers -
Public - is the default access modifier. The variables declared as public can be accessed by methods of any other class outside. public word is used to declare public variables. If there is no access modifier given at the time of variable declaration, by default it is public.
public int pubvar; // Public Class Variable
Private - The variables are declared as private and can be accessed by only the class itself. These variables can not be accessed outside from the class. Even the child classes / sub classes of the class can not access the private variables.
private int privar; // Private Class Variable
Protected - These variables are declared as protected and can be accessed by all the classes in the same package, but only its sub classes in the different package. But other classes in different package, which are not the sub classes, can not access the protected variables.
protected int provar; // Protected Class Variable
Block Variables -
Two enclosing parentheses - opening ({) and closing (}) create a block. Any variables declared between these two parentheses are called block variables and their scope is block itself. The block variables can not be accessed outside from the block. We already know about method as one block -
public void test() {←
int i = 0;
}←
// i = 5; (Variable i is not accessible)
Another example is for loop -
public void test() {
for(int i = 0; i < 5; i++) {←
System.out.println(i);
}←
// System.out.println(i); (Variable i is not accessible)
}
Blocks can be defined with only parentheses also, so the variable can not be accessed outside of the parentheses -
public void test() {
{←
int i = 5;
}←
// System.out.println(i); (Variable i is not accessible)
}
No comments:
Post a Comment