Where should static objects be built in Java?

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

Second question: is there documentation on this type of static initialization? I could find links only to static primitives, but not to 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();
    }
}
+3
source share
1 answer

, , , , , static initializer, :

class A {

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

    //...

, :

private static SClass sc = new SClass();

, , SClass , . , :

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);
    }
}
+5

All Articles