Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

java - Why is it called an "anonymous" inner class?

Just today I needed a way to pass a function around between different objects. I quickly learned that you can't do that directly in Java, but you can pass around an instance of wht is apparently called an "anonymous inner class", like so:

To define the class:

interface MyCallback {
    public int execute(int i1, int i2);
}

To make an instance of it:

MyCallback callback = new MyCallback() {
    public int execute(int i1, int i2) {
        return i1 + i2;
    }
};

And to call it:

int sum = callback.execute(1, 2);  // Sets sum to 3.

Simple enough. But what I don't understand is why it is called "anonymous". Didn't I just give it the name MyCallback? And a thing that is named can't be anonymous, right? Please help me out of my confusion about this terminology.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No, an anonymous class is a sub type of the type whose name you use to instantiate it.

An anonymous class declaration is automatically derived from a class instance creation expression by the Java compiler.

MyCallback is the name of the super type. Your anonymous sub class class has no name that is useful to the developer at compile time.

The actual class will have a name, something like MyCallback$1, but you won't be able to use it in the source code. For example, you can't do

MyCallback$1 anonymousClassInstance = ...;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...