Access Control, Usage of Static With Data and Methods, Usage of Final With Data, Nested Classes
Access Control, Usage of Static With Data and Methods, Usage of Final With Data, Nested Classes
class UseStatic {
static int a = 3;
static int b;
static void meth(int x) {
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);
}
}
• Here is the output of the program:
Static block initialized.
x = 42
a=3
b = 12
Analysis of the program
• As soon as the UseStatic class is loaded, all of the
static statements are run.
• First, a is set to 3, then the static block executes,
which prints a message and then
initializes b to a * 4 or 12.
• Then main( ) is called,
which calls meth( ), passing 42 to x.
• The three println( ) statements print the two static
variables a and b, and the local variable x.
• Outside of the class in which they are defined,
static methods and variables can be used
independently of any object.
• To do so, specify the name of their class followed
by the dot operator.
• use the following general form:
classname.method( )
classname.variable
End of session