What is an anonymous inner class?

守給你的承諾、 提交于 2019-11-27 08:33:07

问题


When I tried to do some sample on an abstract class in Java I accidentally got some thing like anonymous inner class in Eclipse.

I have pasted the piece of code below. I don't understand how the abstract class is related to anonymous class.

package com.Demo;

abstract class OuterClass {
    abstract void OuterClassMethod();
}

public abstract class InnerClass extends OuterClass {
    public static void main(String[] args) {
        InnerClass myInnerClass = new InnerClass() {
            @Override
            void OuterClassMethod() {
                int OuterClassVariable = 10;
                System.out.println("OuterClassVariable" + " " + OuterClassVariable);
            }
        };
    }
}

回答1:


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.




回答2:


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.




回答3:


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();


来源:https://stackoverflow.com/questions/16392052/what-is-an-anonymous-inner-class

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