I was reading the following code
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
}
});
I am not getting what type of structure we have passed as the argument to the function setOnItemClickListener and how such type of structure works ? If it is a class then why we are using () in front of the class name and how the class functions will be called ? As i said i do not know what type of structure it is , so i do not know how to search it with proper key words on a search engine .
3
It’s a anonymous class.
- setOnItemClickListener takes a instance of the type OnItemClickListener
- on the first line, a instance of the anonymous class is created, the () is the constructor call
- what follows inside the {} is the body of the anonymous class, which in this case, overrides the onItemClick method of OnItemClickListener
Anonymous classes are used when an implementation of a type is used only at one spot in your system.
2
This is an anonymous class. One little-known feature of Java is local classes:
public void method()
{
class MyClass{}
MyClass cls = new myClass();
}
This is allowed. You rarely see it, because in this form it doesn’t serve any real purpose and just looks confusing. But if you want to pass a method some code to be executed, you can also use a shortcut, where you make only one instance of the class and don’t give it a name (hence anonymous).
As noted in the comments, Java 8 introduces closures and lambda expressions, so that blocks of code become real language constructs that can actually be passed around. Before that, anonymous classes was the way to pass blocks of code around.