Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static inner class

 
Yuan Ye
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I studied the static inner class and concluded these. Anyone please correct me if I am wrong.
1. when modifier "static" applying to a class, it can only be applied to a class nested in another class.
2. a static inner class can contain non-static varibles and methods.
3. To access the static methods in a static class, use the class name or class instance, to access the non-static methods in a static class, use class instance.
Thanks
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

1. when modifier "static" applying to a class, it can only be applied to a class nested in another class.

From the JLS, §8.1.1 Class Modifiers:

The access modifier static pertains only to member classes (�8.5, �9.5).

So, yeah, that's right.

2. a static inner class can contain non-static varibles and methods.

From the JLS, §8.1.2 Inner Classes and Enclosing Instances:

Inner classes may inherit static members that are not compile-time constants even though they may not declare them. Nested classes that are not inner classes may declare static members freely, in accordance with the usual rules of the Java programming language. Member interfaces (�8.5) are always implicitly static so they are never considered to be inner classes.

So that's right, too.

3. To access the static methods in a static class, use the class name or class instance, to access the non-static methods in a static class, use class instance.

That's how it is for all static methods and instance methods, regardless of whether or not that class is nested.

One other note - a member class that is given the attribute static is not considered an inner class. Rather, it is called a top-level nested class. A true inner class must have an instance of the enclosing class associated with it - a top-level nested class does not.
I hope that helps,
Corey
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic