【问题标题】:Calling Methods of Anonymous Inner Class in the parent class父类中匿名内部类的调用方法
【发布时间】:2012-06-05 10:30:57
【问题描述】:

我在浏览匿名内部类时遇到以下疑问

这是我下载的 Original 代码并正在解决它(请参阅下面的代码仅针对我的问题)。

根据上面的链接,他们说我们不能在匿名内部类中重载和添加其他方法。

但是当我编译下面的代码时,虽然我无法在 Inner 类之外调用这些公共方法,但它工作正常。

起初我很惊讶为什么我不能访问 Inner 类之外的公共方法,但后来我意识到 Object 由不知道此类函数调用的“父”类引用持有。

我可以在下面的代码中进行哪些更改以调用 Inner 类之外的重载方法和新方法?

class TestAnonymous
{    

    public static void main(String[] args)
    {      
        final int d = 10;

        father f = new father(d);

        father fAnon = new father(d){                
        // override method in superclass father
        void method(int x){     
            System.out.println("Anonymous: " + x);
            method("Anonymous: " + x); //This Compiles and executes fine.
            newMethod(); //This Compiles and executes fine.
        }

        // overload method in superclass father
        public void method(String str) {
            System.out.println("Anonymous: " + str);
        }

        // adding a new method
        public void newMethod() {
            System.out.println("New method in Anonymous");
            someOtherMethod(); //This Compiles and executes too.
        }

        };

        //fAnon.method("New number");  // compile error
        //fAnon.newMethod();         // compile error - Cannot find Symbol

    }

    public static final void someOtherMethod()
    {
        System.out.println("This is in Some other Method.");
    }

} // end of ParentClass

class father
{   
    static int y;

    father(int x){ 
        y = x;
        this.method(y);
    }

    void method(int x){
        System.out.println("integer in inner class is: " +x);
    }     
}  

【问题讨论】:

    标签: java overloading anonymous-class


    【解决方案1】:

    你不能用匿名类做到这一点;它与 Java 的静态类型系统冲突。 从概念上讲,变量fAnon 的类型为father,它没有.method(String).newMethod 方法。

    您想要的是father 的普通(命名)子类:

    class fatherSubclass extends father
    { /* ... */ }
    

    你应该声明你的新变量

    fatherSubclass fAnon = new fatherSubclass(d)
    

    【讨论】:

      【解决方案2】:

      我可以在下面的代码中进行哪些更改以调用 Inner 类之外的重载方法和新方法?

      只需将其 设为匿名类即可。您可以在方法中声明类:

      public static void main(String[] args) {
          class Foo extends Father {
              ...
          }
          Foo foo = new Foo();
          foo.method("Hello");
      }
      

      ...但我可能会建议将其设为一个单独的类,必要时嵌套在外部类中,或者只是一个新的顶级类。

      一旦你开始想用匿名类做任何复杂的事情,通常最好把它分解成一个成熟的命名类。

      【讨论】:

        【解决方案3】:

        您不能从匿名类外部调用“重载”和新方法。你可以在你的匿名班级里打电话给他们,但不能从外面打电话。外界根本不知道他们。没有包含有关它们的信息的类或接口规范。

        【讨论】:

        • 是的,我在发布这个问题时就知道了这种行为。
        • @Sudhaker:那为什么要问这个问题?
        • 我想要一种从外面给他们打电话的方式,所以要求解决问题,Snail 和 Jon 的回答正是我所期待的......
        猜你喜欢
        • 2016-08-05
        • 2012-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-19
        • 1970-01-01
        相关资源
        最近更新 更多