Why is a static class illegal in Java?

JDx picture JDx · Aug 6, 2012 · Viewed 72k times · Source

I'm developing an Android application but have hit a bit of a brick wall, I keep getting the error:

Illegal modifier for the class FavsPopupFragment; only public, abstract & final are permitted

This happened after following this answer to another SO question. Here is the code that I have:

package com.package.name;

/* Imports were here */

public static class FavsPopupFragment extends SherlockDialogFragment {

    static FavsPopupFragment newInstance() {
        FavsPopupFragment frag = new FavsPopupFragment();
        return frag;
    }
}

The error appears on the class name. I don't understand why this won't work, please help. Thank you.

Answer

Sanjay T. Sharma picture Sanjay T. Sharma · Aug 6, 2012

You can't create a top level static class; that's what the compiler is trying to tell you. Also have a look at the answer here as to why this is the case. The gist is:

What the static boils down to is that an instance of the class can stand on its own. Or, the other way around: a non-static inner class (= instance inner class) cannot exist without an instance of the outer class. Since a top-level class does not have an outer class, it can't be anything but static.

Because all top-level classes are static, having the static keyword in a top-level class definition is pointless.