Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should static objects be constructed in Java?

Tags:

java

In the following code, where should sc be constructed? Without the line "sc = new SClass()", I get a null pointer exception, but I'm not sure if that's the right place for it. I tried using a static initializer block, but that gave me a compiler error.

Second question is, is there documentation on this type of static intialization? I could only find references to static primitives, but not static objects.

class A {
    private class SClass{
        String s;
        String t;
    }

    private static SClass sc;

    public void StringTest() {
        sc = new SClass();
        sc.s = "StringTest";
        System.out.println(sc.s);
    }
}

public class Test {
    public static void main(String[] args) {
        A a = new A();
        a.StringTest();
    }
}
like image 417
Ravi Avatar asked Jun 01 '26 11:06

Ravi


1 Answers

If you find you have several things that are static that need some instantiation, or if you have non-trivial work to do, as in this case, you can use a static initializer block, they look something like this:

class A {

    static {
        sc = new SClass();
        sc.s = "StringTest";
        System.out.println(sc.s);
    }

    //...

You can also define it where you declare it for simpler cases:

private static SClass sc = new SClass();

Additionally, you have a complicated issue here because you fail to define SClass as a static class, but you intend to use it statically. The inner class should have a static qualifier on it, the code below should work:

class A {
    private static class SClass{
        String s;
        String t;
    }

    private static SClass sc;

    static {
        sc = new SClass();
        sc.s = "StringTest";
        System.out.println(sc.s);
    }
}
like image 107
Mark Elliot Avatar answered Jun 03 '26 02:06

Mark Elliot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!