In Java, a class can never be qualified to be either private or protected. It can simply be public all the times. It’s quite obvious, there is no question about it.
Inner classes in Java however, can be designated with any of these modifiers private, protected or public. An inner class can also be defined within an individual block like a method. In such a case, an inner class can not be designated with any of these modifiers, private, public or protected.
The following simple program is compiled with no errors and works just fine.
package amazingjava;
final class Demo
{
public class Really
{
public class Quite
{
public class Surprising
{
@Override
public String toString()
{
return( "it really works !" );
}
}
}
}
}
final public class Main
{
public static void main(String[] args)
{
System.out.println( "It may be hard to believe, but " + new Demo().new
Really().new Quite().new Surprising().toString());
class Really
{
class Quite
{
class Surprising
{
@Override
public String toString()
{
return( "it really works !" );
}
}
}
}
System.out.println( "It may be hard to believe, but " + new Really().new
Quite().new Surprising().toString());
}
}
It produces the following output.
It may be hard to believe, but it really works !
It may be hard to believe, but it really works !
Now, my question is only that the inner classes declared inside the main() method in the above example can not have any modifiers. An attempt to qualify those classes with any of modifiers private, protected or even public issues a compile time error! Why? Which default modifier is used by the compiler in such cases?
A inner class defined inside a method is treated as any variable declared in that method – and those variables are LOCAL. A local variable or class cannot have any modifiers besides FINAL.
The inner classes defined within another class are treated as instance variables, thus an instance class or a variable can be public private or have no identifier.