I am refactoring a class with a public facing interface and thinking about the usage led me to ask:
What is the difference between declaring the following within some larger class (as an instance variable):
private final OnClickListener mButtonOnClickListener = new OnClickListener() {
@Override
public void onClick(View view) {
//some codes
}
};
vs declaring as an anonymous inner class as follows (on the fly):
private void someFunctionInClass() {
someOtherFunctionThatTakesAnOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
//some codes
}
});
}
More specifically, is the former still considered an anonymous inner class? I read in this answer that an anonymous inner class
is one that is created AND defined within the body of another class' method
The first example I gave is created and defined within the body of another class but not within another class' method as the second one is. Is it still an anonymous inner class? Furthermore, what is the accepted practice for one vs. another? Is it more efficient to declare (what I think is still) an anonymous inner class as an instance variable because new objects don't need to be recreated?