Class variables are the variables declared with the static modifier as a field of a class. These variables are created and initialized during the class loading itself and only one copy of such variables is shared among all the instances of the class. The objects only contain a reference to that single copy, so changes made on such variables using any object reference will be visible across all the object references. We normally use the name of the class to access such variables.
Member variables belong to a particular instance of a class and one copy of such a variable is created every time an object of the class is created. Since, all the instances keep their own copies of a member variable, so changes made using one object reference will be local to that reference only. Such variables can be used on an object reference only and not on a class name as member variables have no existence without the corresponding object. These variables are initialized just before the constructor is called.
Local variables are the variables declared locally inside a method definition or the variables which are defined as the parameters of a method. The scope of such a variable is limited to that method only. Local variables defined inside a method definition need to be initialized explicitly otherwise the code will throw a compile-time error.
No comments:
Post a Comment