What is an anonymous inner class?

狂风中的少年 提交于 2019-11-28 14:30:49

A anonymous class is an "in-line" concrete implementation of a class, typically (but not necessarily) of an abstract class or an interface. It is technically a subclass of the extended/implemented super class.

Google for more.

In your example, your class (InnerClass) extends class (OuterClass) and implementing their abstract methods which is the typical behavior of extending an abstract class. In the same way if your class implementing any interfaces you have to override their abstract methods. This is the way to implement Anonymous inner class.

Basically, an anonymous class is an implementation that has no name -- hence the "anonymous" bit.

This particular bit is what makes your class anonymous:

    InnerClass myInnerClass = new InnerClass() {
        @Override
        void OuterClassMethod() {
            int OuterClassVariable = 10;
            System.out.println("OuterClassVariable" + " " + OuterClassVariable);
        }
    };

In normal class instantiations, you would just use:

InnerClass myInnerClass = new InnerClass();

but in this case, you are specifying a new implementation of that class, by overriding a function (OuterClassMethod()) within it. In other instances of InnerClass, OuterClassMethod() will still have its original implementation, because you only adapted this particular instance of InnerClass, and did not store this new implementation in a new class.

If you don't want anonymous classes, do this instead:

Somewhere, specify AnotherInnerClass to extend InnerClass, and to override that function:

class AnotherInnerClass extends InnerClass {
    @Override
    void OuterClassMethod() {
        int OuterClassVariable = 10;
        System.out.println("OuterClassVariable" + " " + OuterClassVariable);
    }
};

And then instantiate it as such:

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