Java内部类遮蔽外部类 [英] Java Inner class shadowing external class

查看:205
本文介绍了Java内部类遮蔽外部类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从K& B书SCJP Sun Certified Programmer for Java 6学习指南中获取了以下代码:

I took the following code from the K&B book "SCJP Sun Certified Programmer for Java 6 Study Guide":

class A { // 1
    void m() { 
        System.out.println("outer"); 
    } 
}

public class TestInners {

    public static void main(String[] args) {

        new TestInners().go();

    }

    void go() {

        new A().m();

        class A { // 2
            void m() { 
                System.out.println("inner"); 
            } 
        }

    }

    class A { // 3
        void m() { 
            System.out.println("middle"); 
        } 
    }
}

这个代码打印中间。我推断标记为3的类声明是阴影的标记为1,这是TestInners类外部。
如果类在不同的包中,我可以通过使用包名称限定其中一个来解决歧义。但在这种情况下,类不仅在同一个包中,而且在同一个文件中。如何获得外部类的实例?

As stated in the book, this code prints "middle". I infer that the class declaration marked as "3" is shadowing the one marked as "1", which is external to TestInners class. If the classes were in different packages, I could resolve the ambiguity by qualifying one of them with the package name. But in this case the classes are not only in the same package but in the same file. How can I get an instance of the external class?

我看到同样的问题这里,但接受的答案意味着修改代码为整个事物添加一个封闭类。我的问题是如何使用任何类型的限定符或引用来获取实例。

I saw the same question here but the accepted answer implies to modify the code adding an enclosing class to the whole thing. My question is how to get the instance using any type of qualifier or reference, if it's even possible.

推荐答案

in package com.test ,所有你需要做的是使用

Assuming your class is in package com.test, all you need to do is use

new com.test.A().m();

使用类的完全限定名称。

using the fully qualified name of the class.

如果您的类在默认包中,即。没有 package 声明,那么你运气不好,不能访问外部 A

If your classes are in the default package, ie. no package declaration, then you are out of luck and can't access the outer A.

这篇关于Java内部类遮蔽外部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆