【问题标题】:Puzzle on Inner Classes and Class Hiding内部类和类隐藏之谜
【发布时间】:2012-04-20 07:55:44
【问题描述】:

我有一个基于inner 类的示例代码要解决:

package inner;

class A {
    void m() {
        System.out.println("Outer");
    }
}

public class TestInner {
    public static void main(String[] args) {
        new TestInner().go();       
    }

    private void go() {
        new A().m();
        class A{
            void m(){
                System.out.println("Inner");
            }
        }
        new A().m();
    }
    class A{
            void m(){
            System.out.println("Middle");
        }
    }
}

上面示例代码给出的输出是:

Middle 
Inner

我的问题是,鉴于我不想使用包名来创建对象,我如何将输出打印为:

Outer
Inner

【问题讨论】:

  • 你有 2 个小时。没有拼写错误。
  • 当且仅当从现在开始绝对必要时,请使用粗体字。
  • 这是一个非常人为的谜题,我看不出它有什么有趣的地方,因为它只是关于命名空间。在您遇到编译单元内的第二个包私有类之前,您将不得不看到数百万行生产级 Java。

标签: java class inner-classes


【解决方案1】:

由于使用包显然是答案,我假设您正在寻找一些迟钝的东西。

你可以添加一个外部类并调用它。

class B extends A { }

// in TestInner.go()
    new B().m();
    class A{
        void m(){
            System.out.println("Inner");
        }
    }
    new A().m();

【讨论】:

  • 我有一个更好的:System.out.println("Outer\nInner"); 这是一个很好的答案:)
【解决方案2】:
public class TestInner {
public static void main(String[] args) {
    new TestInner().go();       
}

private void go() {
    new inner.A().m();        //will produce output "Outer"
    class A{
        void m(){
            System.out.println("Inner");
        }
    }
    new A().m();             //will produce output "Inner"
}
class A{
        void m(){
        System.out.println("Middle");
    }
}

【讨论】:

    猜你喜欢
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 2011-09-01
    相关资源
    最近更新 更多