class
Static value initialization
With this example we are going to demonstrate how to make static values initialization in classes. In short, to make static values initialization in classes we have followed the steps below:
- We have created a class
A
with a methodfunction1(int i)
. - We have also created class
B
, that has two staticA
fields,b1
andb2
. In its constructor it callsfunction1(int i)
ofA b2
field. It also has a methodfunction2(int i)
. - Another class we have created is
C
, that has a fieldA b3
, and twostatic
fieldsA b4
andA b5
. In its constructor it callsfunction1(int i)
ofA b4
field and it also has a methodfunction3(int i)
. - In
StaticInitial
class, we have astatic B t2
field that is initialized usingB()
constructor. First its twostatic
fields are initialized and then inB()
constructorfunction1()
is called. - In
StaticInitial
class anotherstatic
field is initialized, that isC t3
. All static fields ofC
are initialized, and then the nonstatic
field is initialized and the constructor is called, that invokesfunction1()
method ofA
. - A
main()
method inStaticInitial
is called, where we create a new instance ofC
class. Its non static field is initialized and then its constructor is called, that callsfunction1()
.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; class A { A(int i) { System.out.println("A(" + i + ")"); } void function1(int i) { System.out.println("function1(" + i + ")"); } } class B { static A b1 = new A(1); B() { System.out.println("B()"); b2.function1(1); } void function2(int i) { System.out.println("function2(" + i + ")"); } static A b2 = new A(2); } class C { A b3 = new A(3); static A b4 = new A(4); C() { System.out.println("Cupboard()"); b4.function1(2); } void function3(int i) { System.out.println("function3(" + i + ")"); } static A b5 = new A(5); } public class StaticInitial { public static void main(String[] args) { System.out.println("Creating new C() in main"); new C(); System.out.println("Creating new C() in main"); new C(); t2.function2(1); t3.function3(1); } static B t2 = new B(); static C t3 = new C(); }
Output:
A(1)
A(2)
B()
function1(1)
A(4)
A(5)
A(3)
Cupboard()
function1(2)
Creating new C() in main
A(3)
Cupboard()
function1(2)
Creating new C() in main
A(3)
Cupboard()
function1(2)
function2(1)
function3(1)
This was an example of how to make static values initialization in classes in Java.