Today, some other developer found an XML schema with some interesting nesting, which JAXB compiled into a structure like this:
public class Choices
{
public static class Choice
{
public static class Choice
{
}
}
}
If you try to compile this, the Java compiler says,
class Choices.Choice is already defined in class Choices
with of course, the underline on the innermost class Choice
declaration.
But I say, class Choices.Choice
is not what it was trying to declare. Rather, it was trying to declare Choices.Choice.Choice
, which would be a different class.
Interestingly, this is fine:
public class OuterClass
{
public static class Inner1
{
public static class Inner2
{
}
}
public static class Inner2
{
public static class Inner1
{
}
}
}
But this is banned:
public class OuterClass
{
public static class Inner1
{
public static class Inner2
{
public static class Inner1
{
}
}
}
}
So I guess the rule is that the name of a class can't be the same as a containing class at any level. Obviously the fix here is already known- get JAXB not to generate invalid code.
But my question is, why is this restriction even present? What is the Java compiler trying to avoid by not letting us create an inner class with the same name as a containing class?
You can only have inner classes one level deep. Save this answer.
There is no limitations for inner class in salesforce.
Inner Classes As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.
Rules of Local Inner Class:The scope of the local inner class is restricted to the block they are defined in. A local inner class cannot be instantiated from outside the block where it is created in. Till JDK 7, the Local inner class can access only the final local variable of the enclosing block.
Java lets you refer to an outer class without fully specifying its name, like this:
public static class Inner1
{
public static class Inner2
{
public static class Inner3
{
public void demo() {
Class<Inner2> c = Inner2.class; // This is allowed
}
}
}
}
Had nesting of classes allowed the use of identical names at any level of hierarchy, referencing by unqualified name would have been impossible. It is this ability that the Java compiler is trying to preserve by prohibiting nested declarations to collide with names of their outer classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With