Search code examples
javastaticprogram-entry-point

Static Classes, Methods and main()


So, I'm a java noob and i just came across something that confused me. Getting to the point, I made a Foo Class and made an instance:

public class Main 
{
    public static void main(String[] args)
    {
        Foo foo = new Foo("Foo");
    }
}

class Foo
{
    public Foo(String A)
    {
        System.out.println(A);
    }
}

I noted that the Foo Class doesn't have to be static. Why? Whereas

if i do this

public class Main 
{
    public static void main(String[] args)
    {
        Foo foo = new Foo("Foo");
    }
    static class Foo
    {
        public Foo(String A)
        {
            System.out.println(A);
        }
    }
}

Then it HAS to be static. Why the difference? Static means it's instance independent hence every thing that is used in a static method also has to be instance independent(?) With Foo I was creating the instance in the static method so Foo didn't need to be static. But then what difference does having the class inside make? I thought i'd got the concept of static down. but apparently i lack a lot of concepts.


Solution

  • This is covered by JLS-8.1.3. Inner Classes and Enclosing Instances which says (in part)

    An inner class is a nested class that is not explicitly or implicitly declared static.

    An inner class may be a non-static member class (§8.5), a local class (§14.3), or an anonymous class (§15.9.5). A member class of an interface is implicitly static (§9.5) so is never considered to be an inner class.

    A static class is thus not an inner class, and an inner class requires an instance of the enclosing class; like

    public class Main {
        public static void main(String[] args)
        {
            Foo foo = new Main().new Foo("Foo");
        }
        class Foo
        {
            public Foo(String A)
            {
                System.out.println(A);
            }
        }
    }