开发者

Where should static objects be constructed in 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();
    }
}


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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜