File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes no static method in inner class - why ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "no static method in inner class - why ?" Watch "no static method in inner class - why ?" New topic

no static method in inner class - why ?

ankur rathi
Ranch Hand

Joined: Oct 11, 2004
Posts: 3830

after compilation there will be two class files : Outer.class & Outer$Inner.class

When we will run this inner class with java Outer$Inner command this will give an error NoSuchMethodExist . Because it doesn't have a main method .And we can't have a main method in inner class because this method has static in its signature .

Now my question is why inner class can't have static methods ???

thanks a lot .
[ January 13, 2005: Message edited by: rathi ji ]
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
You must never use the generated Outer$Inner.class file. In the case of your class and it's inner class you must have an instance of the outer class to be able to create an instance of its inner class.

"why inner class can't have static methods ???"

Because the JLS 8.1.2 says they can't.

And the Java Tutorial says
"Also, because an inner class is associated with an instance, it cannot define any static members itself."
[ January 13, 2005: Message edited by: Barry Gaunt ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
You can do this:

The outer class can be an instance class and the nested class could be static. This way you can implement static void main in the nested class and it will run.
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
But remember, a static nested class is not an inner class.

Mike Gershman
SCJP 1.4, SCWCD in process
subject: no static method in inner class - why ?
Similar Threads
K&B doubt: Inner class name from static context of outer class
confused question
Why static methods can't be defined inside Inner classes
Inner Class
inner class