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 A that has a method func(int val) that prints the given int value.
  • We also have a class B, that has two static A objects and in a static clause creates two new instances of the two A objects.
  • We call the func() method of a1 field of B in a main() 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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button