class
Static clause initialization
This is an example of how to make a static clause initialization. In order to do so, we have created two classes as described below:
- We have a class
Athat has a methodfunc(int val)that prints the given int value. - We also have a class
B, that has twostaticAobjects and in astaticclause creates two new instances of the twoAobjects. - We call the
func()method of a1 field of B in amain()method.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core;
class A {
A(int val) {
System.out.println("A(" + val + ")");
}
void func(int val) {
System.out.println("func(" + val + ")");
}
}
class B {
static A a1;
static A a2;
static {
a1 = new A(1);
a2 = new A(2);
}
B() {
System.out.println("B()");
}
}
public class StaticClause {
public static void main(String[] args) {
System.out.println("Inside main()");
B.a1.func(99); // (1)
}
//uncoment the following code and see what happens
// static B x = new B(); // (2)
// static B y = new B(); // (2)
}
Output:
Inside main()
A(1)
A(2)
func(99)
This was an example of how to make a static clause initialization in Java.
