繁体   English   中英

在父类中调用匿名内部类的方法

[英]Calling Methods of Anonymous Inner Class in the parent class

关于Anonymous内心阶级的冲浪,我对此产生了疑问

这是我下载的原始代码并正在解决它(请参阅以下代码仅用于我的问题)。

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

但是当我编译下面的它工作正常,虽然我无法在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的静态类型系统冲突。 从概念上讲,变量fAnon的类型为father ,它没有.method(String).newMethod方法。

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

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

你应该声明你的新变量

fatherSubclass fAnon = new fatherSubclass(d)

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

只是让它不是一个匿名的类。 可以在方法中声明该类:

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

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

一旦你开始想要做任何复杂的匿名类,通常最好将它分解为一个完全成熟的命名类。

您无法从匿名类外部调用“重载”和新方法。 您可以在匿名课程中调用它们,但绝不能从外部调用它们。 外面的世界根本不知道它们。 没有关于它们的信息的类或接口规范。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM