Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

needs explanation

 
Venkat Ramsimha
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class StaticNestedClassImp
{
String name = "ramu";
public static void main(String args[])
{
method();
StaticNestedClassImp.Nested nc = new StaticNestedClassImp.Nested();
nc.method1();
}
public static void method()
{
String sal = "tenthosand";
static class Nested
{
public void method1()
{
System.out.println("in the nested method");
}
}
}
}
WHY THE ABOVE PROGRAM WITH RESPECTIVE TO "STATIC NESTED CLASSES" IS GIVING "COMPILE TIME ERRORS"

can anybody provide the explanation?

thanks,
venkat
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, "local" classes (e.g., those defined within a method body) cannot be static. Second, since they are defined within the scope of the method body, local classes are essentially "private" to that block -- just like a local variable.

If you move the nested class definition outside of the method, this code will compile. In fact, if you keep the class definition static, you don't need an instance of the enclosing class. You can simply say...

Nested nc = new Nested();
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic