Whenever I use nested classes, I give them names not including the outer class name, e.g.,
MySomething.Kind
and not MySomething.MySomethingKind
. The nested classes are sometimes visible to the outside and then I want to refer to them always by the name qualified by the enclosing class, i.e., MySomething.Kind
and not just Kind
. Sometimes there are multiple classes containing a nested Kind
, so using the unqualified name may be confusing.
Is there any way to prevent Eclipse from needlessly importing mypackage.MySomething.Kind
instead of using (already imported) mypackage.MySomething
together with the semi-qualified name?
This doesn't happen spontaneously. As stated by jprete, when I always use the semi-qualified name, the nested class doesn't get imported. But any refactoring creating a variable of type MySomething.Kind
declares it as Kind
only and adds the unwanted import statement. This turns the refactoring to useless, as I have to edit it manually. Whenever I forget, I get the worst of both: a mixture of unqualified and semi-qualified names.
Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass , a nested class can be declared private , public , protected , or package private.
Which feature of OOP reduces the use of nested classes? Explanation: Using inheritance we can have the security of the class being inherited. The subclass can access the members of parent class. And have more feature than a nested class being used.
A static nested class cannot access non-static members of its outer class because it does not have an implicit reference to an outer object. 4. Non-static members of a normal inner class can access the static members of any static nested class within the same outer class.
Nested Class can be used whenever you want to create more than once instance of the class or whenever you want to make that type more available. Nested Class increases the encapsulations as well as it will lead to more readable and maintainable code.
I have found that, if I always refer to the nested class with the "semi-qualified" name - i.e. MySomething.Kind
rather than Kind
- that Eclipse will not try to automatically add import mypackage.MySomething.Kind
when I tell it to reorganize imports, but instead will only add import mypackage.MySomething
and leave the "Class.NestedClass" references alone.
It looks like there's no solution, but what I'm doing now is pretty practical (when used in a script):
find src -name "*.java" | xargs perl -pi -e \
's/^(import [.\w]+\.)([A-Z]\w+)(\..*);/$1$2;/;'
It simply replaces all the unwanted imports like
import java.util.Map.Entry;
by the outer class imports like
import java.util.Map;
It's matter of seconds to fix the errors manually and let organize imports get rid of duplicates. It ignores static imports as I want.
Warnings:
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