Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

can inner classes be private/protected/static

 
sun par
Ranch Hand
Posts: 257
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can top level nested classes be marked private, protected or static?
Just read from the RHE book summary that classes cannot be protected...
Am confused..
Please help
Thanks
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sunita
A top level nested class is a nested class marked static. According to the JLS sect 8.1.1 any class can be declared public. Only nested classes can be declared private or protected. A static nested class is a top level class so it can only be public.
Hope that helps
 
sun par
Ranch Hand
Posts: 257
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Dave... Much clearer now
 
Alfred Kemety
Ranch Hand
Posts: 279
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code generates the following errors

-------
C:\Documents and Settings\Administrator\My Documents\Test.java:7: illegal start of expression
private static class StaticLocalClass {
^
C:\Documents and Settings\Administrator\My Documents\Test.java:7: ';' expected
private static class StaticLocalClass {
^
C:\Documents and Settings\Administrator\My Documents\Test.java:9: illegal start of expression
private class NonStaticLocalClass {
^
C:\Documents and Settings\Administrator\My Documents\Test.java:9: ';' expected
private class NonStaticLocalClass {
^
C:\Documents and Settings\Administrator\My Documents\Test.java:11: illegal start of expression
static class StaticLocalClass_ {
^
C:\Documents and Settings\Administrator\My Documents\Test.java:11: ';' expected
static class StaticLocalClass_ {
^
C:\Documents and Settings\Administrator\My Documents\Test.java:17: illegal start of expression
static class StaticLocalClass2 {
^
C:\Documents and Settings\Administrator\My Documents\Test.java:17: ';' expected
static class StaticLocalClass2 {
^
8 errors
-------
I deduce from the code and the errors the following:
1- Top level Static/Non-Static nested classes can be declared static or protected/private or a combination of both (i.e: private static), also if the top level nested class is not static, it can still be declared private and protected or left with no access modifier to be with package access. It can as well be declared final or abstract.
2- Local classes - meaning declared inside a method - can't be declared protected or private, just like any local variable, it can't also be declared static. Yet it can be declared final or abstract.
* the fact that the method is static or not doesn't affect the last deduction, it affects access to members though.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic