Monday, 20 January 2014

UNDERSTANDING static


The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.Instance variables declared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable.The static keyword can be used in 3 scenarios,they are  static variables,static methods and static blocks of code.

Methods declared as static have several restrictions:
  • They can only call other static methods.
  • They must only access static data.
  • They cannot refer to this or super in any way. (The keyword super relates to inheritance.)

Example for static keyword:

class StaticDemo 

static int a = 42; 
static int b = 99; 
static void callme() 

System.out.println("a = " + a); 


class StaticByName { 
public static void main(String args[]) 

StaticDemo.callme(); 
System.out.println("b = " + StaticDemo.b); 



Here is the output of this program: 
a = 42 
b = 99

No comments:

Post a Comment