Saturday, September 26, 2015

Static variable and Static method:

In Java Variables can be declared with the “static” keyword.
Example: static int y = 0;
When a variable is declared with the keyword “static”, its called a “class variable”. A static variable always belongs to the class and not to the object . Since all instances share the same copy of the variable, a class variable can be accessed directly with the class, without the need to create an instance i.e an object. 
  • single copy to be shared by all instances of the class
  • A static variable can be accessed directly by the class name and doesn’t need any object

Using static variable of another classes

If you wish to call static variable of another class then you have to write class name while calling static variable as shown in example below.
                                                                                                                                                                     STATIC VARIABLE DEMO:
Here, convertMpgToKpl  variable is made static. Now the value of convertMpgToKpl would be constant for a class. Since the constructor is called twice as two object is created(x1 and x2), so the final value of the static variable is 2.
 Whereas the instance variable CarMilage and Carcolor is object dependent, for x object CarMilage value is 20 and for x2 object it's value is 50.

Same is true for static method, in order to access or call the static method one need not create an object.  Syntax:<class-name>.<method-name>

why you wouldn't want to create a static method?
Basically, polymorphism goes out of the window. You'll not be able to override the method, nor declare it in an interface. It takes a lot of flexibility out from your design. 

No comments:

Post a Comment