Scope of a variable determines the area in which a variable can be accessed.
Java variables are actually classified into three kinds:
1. instance variables,
2. class variables, and
3. local variables.
Instance and class variables are declared inside a class. They are accessible throughout the class. If these are ‘public’ type, they are also accessible outside but with the objects or with class-name when it is a class variable. Whereas local variables are accessible only in the methods in which they are declared.
Instance Variables: Instance variables are created when the objects are instantiated and therefore they are associated with the objects. They take different values for each object.
Class variables are global to a class and belong to the entire set of objects that class creates. Only one memory location is created for each class variable. These are basically static data members of a class. They take common value for all the objects.
Local variables: Variables declared and used inside methods are called local variables. They are called so because they are not available for use outside the method definition. Local variables can also be declared inside program blocks that are defined between an opening brace ‘{‘ and a closing brace ‘}’. These variables are visible to the program only from the beginning of its program block to the end of the program block. When the program control leaves a block, all the variables in the block will cease to exist.
0 comments:
Post a Comment