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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…