| written 9.1 years ago by | • modified 9.1 years ago |
Mumbai University > Information Technology > Sem 3 > Object Oriented Programming Methodology
Marks: 5M
Year: Dec 2013, May 2014, May 2015
| written 9.1 years ago by | • modified 9.1 years ago |
Mumbai University > Information Technology > Sem 3 > Object Oriented Programming Methodology
Marks: 5M
Year: Dec 2013, May 2014, May 2015
| written 9.1 years ago by |
The following example shows a class that has a static method, some static variables, and a static initialization block:
class UseStatic {
static int a = 3; //declaring static variable
static int b;
static void meth(int x) { //defining static method
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42); //calling static method
}
}//end of class
on as the UseStatic class is loaded, all of the static statements are run. First, a is set to 3, then the static block executes (printing a message), and finally, b is initialized to a * 4 or 12. Then main() is called, which calls meth( ), passing 42 to x.
The three println( ) statements refer to the two static variables a and b, as well as to the local variable x.(It is illegal to refer to any instance variables inside of a static method.)
Here is the output of the program:
Static block initialized.
x = 42
a = 3
b = 12
Outside of the class in which they are defined, static methods and variables can be used independently of any object. To do so, you need only specify the name of their class followed by the dot operator. For example, if you wish to call a static method from outside its class, you can do so using the following general form: classname.method( )