Search code examples
javastatic-classes

Creating an instance of static nested class in Java


I have read the posts on differences between static nested classes and inner classes. My question is more of an idiomatic java one.

My requirement was to demonstrate various concepts like inheritance using a Single piece of code in Java. A single class file, so that it can be studied top-down and verified by running in sandbox like ideone - http://ideone.com/jsHePB

class SOFieldAccessQuestion {

    static class B {
        int vf;
        static int sf;

        B(int i) {
            vf = i;
            sf = i + 1;
        }
    }

    static class C extends B {
        int vf;
        static int sf;
        C(int i) {
            super(i+20);
            vf = i;
            sf = i + 2;
        }
    }

    public static void main(String[] args) {

        // Is it Okay to create an instance of static nested class?

        C c1 = new C(100);
        B b1 = c1;

        System.out.println("B.sf = " + B.sf + ", b1.sf = " + b1.sf);
        System.out.println("C.sf = " + C.sf + ", c1.sf = " + c1.sf);

        System.out.println("b1.vf = " + b1.vf);
        System.out.println("c1.vf = " + c1.vf);
    }

}

My question is, is it okay to create an instance of a static nested class like above? I fear that I am ignoring the meaning of "static" here. How should I refer and acknowledge the concept that Java allows me to create objects of static class.

If I don't create a static class of B or C, then I can't use them inside public static void main method and may not execute the program with a main entry point and thus I am forced to do it.


Solution

  • is it okay to create an instance of a static nested class like above?

    Yes, it is. For example, look at the various nested classes in java.util.Collections.

    How should I refer and acknowledge the concept that Java allows me to create objects of static class.

    A static class within a class is called a nested class. The containing concept is known as a member class, which is (more or less) like any other member of a class. Being a static member, the nested class belongs to the containing class, not to its instances.

    If I don't create a static class of B or C, then I can't use them inside public static void main method and may not execute the program with a main entry point and thus I am forced to do it.

    You can still declare your classes outside your SOFieldAccessQuestion but in the same .java file. They just can't be public.