Why do I have to import a nested class in the class it is defined?
compiler-construction, java
Solution
A declaration is visible in the scope it occurs in, and for members, that scope is the stuff between the enclosing curly brackets, or as the spec puts it:
The scope of a declaration of a member `m` declared in or inherited by a class type `C` (§8.1.6) is the entire body of `C`, including any nested type declarations.
Why it has been defined that way is something only the creators of Java can answer with any degree of certainty, but I suspect they wanted as simple a rule as possible, and saying that all members, variables and so on are visible within the surrounding curly brackets is a very simple rule.
And by the way: You are not required to import the type, you can use a qualified name instead. In your example, that would read:
public class Example implements Iterable<Example.Nested> { }
Problem
In the following example the `import` is necessary, otherwise Java's compiler will complain that `Nested` cannot be resolved to a type in `Iterable<Nested>`: ``` package test; import test.Example.Nested; public class Example implements Iterable<Nested> { public final static class Nested {} } ``` (using `Iterable<Example.Nested>` instead of an import works as well) This only happens when referencing a nested class in the definition of the outer class, e.g. when using it as a parametric type, but also when extending/implementing it (which will result in another error once the compiler can resolve the class), or when using it as or in an annotation. My question is: Why can't the compiler find the nested class without an explicit declaration?