Java inner class with the same name as other top level class

跟風遠走 提交于 2019-12-04 08:47:29

Use the fully qualified class name:

new com.mypackage.A();

If your classes are in packages, I'd expect that to be the simplest way of achieving this. I don't believe there's any equivalent of the C# global:: for Java, to force this sort of thing.

Ultimately though, I'd just try to change the class names to avoid the problem happening in the first place. That's usually a better approach than using workarounds.

You should provide different package names for your two As so that they are clearly different types, then you can reference them by their full names.

For example:

my.package.for.toplevel.A outerA = new my.package.for.toplevel.A(); // prints "A outer"
                                                                    // if this is the
                                                                    // package

Or even better, use two different names for two distinct classes.

The name of the inner class is said to shadow the name of the top-level class. The top-level class cannot be referenced by its simple name in the scope of the inner class; the top-level class can only be referenced via a qualified name.

If the top-level class is in the default package (in which case its canonical name is the same as its simple name), you can still access it via reflection.

Yep, just use packages or avoid naming them the same from the beginning. I wonder what's your reason to name them the same anyway?

To explain your error, it comes from the fact that it tries to access the inner A, but since that class is not declared as static and there's no Main instance available, it can't create a non-static inner A that requires a reference to parent Main instance.

Assumed the classes are in the default package. To resolve naming conflict in this case needs either rename the conflicting classes or use the named package. Then use FQCN to resolve the issue.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!