Static methods in Inner classes

Hit this seldom seen compilation error while writing inner classes.


public class OuterClass {
	public class InnerClass {
		public static void InnerStaticMethod() {
		}
	}
}

This is what the compiler said:

The method InnerStaticMethod cannot be declared static; static methods can only be declared in a static or top level type

Java don’t like inner classes to have static methods, unless the inner class is static. A static inner class means you can instantiate the inner class without an enclosing outer class instance. One quick way to fix this situation is below, but note that you lose access to the outer class instance variables. InnerClass may also be instantiated without an OuterClass by new OuterClass.InnerClass(). Of course this can be prevented by limiting the access of the inner class.


public class OuterClass {
	public static class InnerClass {
		public static void InnerStaticMethod() {
		}
	}
}

Similarly, when the inner class is non-static, static member variables are not allowed. But static finals are permissible.

1 Comment »

  1. Anuj said,

    September 30, 2011 at 12:58 pm

    Good one 🙂 Thanks

RSS feed for comments on this post · TrackBack URL

Leave a Comment