Monday 25 June 2012

JAVA - Variable

Variables:

mostly 2 types
1) instance variable
2) class variable


Instance variable :

    Variables of each instance of a class varies . So same variable names of different instances(object) of same class , point to different memory location . So changing of its value by one object doesn't not get reflected in the variable of other object .

Class variables :

    Here  same variable names of different instances(object) of same class , point to same memory location . So a change made in the variable by one object , gets reflected in other objects variable , as these variables point to same memory location .

Next question that comes is how compiler differentiates between instance variables and class variables . Ya , we have to do that . We use the keyword "static" before variable name to denote it as class variables . Others are instance variables .



How to access these variables ?

Instance variable can be accessed by using the objectname(or so called instancename).instancevariable ;
Classvariable can be accessed by using the classname.classvariable ;


Application of the concept "static" to create constants :



The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.
For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter):
static final double PI = 3.141592653589793;
Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so. By convention, the names of constant values are spelled in uppercase letters. If the name is composed of more than one word, the words are separated by an underscore (_).

 
  

No comments:

Post a Comment