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?
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.
Nested Classes in C++A nested class is a class that is declared in another class. The nested class is also a member variable of the enclosing class and has the same access rights as the other members. However, the member functions of the enclosing class have no special access to the members of a nested class.
As mentioned in the section Nested Classes, nested classes enable you to logically group classes that are only used in one place, increase the use of encapsulation, and create more readable and maintainable code.
Static Nested Class : can't access enclosing class instance and invoke methods on it, so should be used when the nested class doesn't require access to an instance of the enclosing class . A common use of static nested class is to implement a components of the outer object.
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 typeC
(§8.1.6) is the entire body ofC
, 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> { }
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