Tuesday, 3 October 2017

Usage of static keyword in programs


                    Use of static keyword in programs.


In order to wind up the static concepts in java consider the following three rules.



Rule 1:  “The value of the static variable remains same for all the objects formed from the same class. Each object shares the common value of the variable. Any change in the value of the static variable is reflected in all objects of that class ".




To illustrate the above mentioned rule consider the below given program.






In the above example variable x had value 10 when it was changes to 20 the value is shared by the objects obj2, obj3 which are created from the same class whereas in case of an instance variable the value is not shared by the object created from the same class.



Rule 2:  When you declare the method as static it can be accessed in another class without creating an object but by using classname and dot operator. The variable is declared as static and is called class variable".




Consider the below program to demonstrate the above rule.



In the above program the static member ‘a’ and the static method display()’ is called without creating the object and is accessed using the class name followed by dot operator.




Rule 3: Within a class, static member can be accessed by static members only.”




Consider the below program which illustrates rule 3.





In the above program the method display() which is defined as static is called  in the method main which is also defined as static.



Please do comment.









             The `this` keyword in java The this keyword in java can be used for different purposes. Some of these are listed below. ...