Reputation:
Hello i have recently started programming in java especially on android, since im new to java , i found something that i dont understand.
theListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String pickedLanguage = "Your favorite programming language is : " + String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(MainActivity.this,pickedLanguage,Toast.LENGTH_LONG).show();
}
});
What i dont understand:
setOnItemClickListener
contains in its parameter list a new class ? how is this possible ? whats going on ? i just read a tutorial about classes and it says class should be in a single file and should have the same name as the file , and basically what does this mean ? the sample code i pasted says create a new instance from this function which belongs to adapter view ? i thought you can create only a new object not just a function from object, i basicaly dont understand the whole code , how is it possible that there is a new class defined inside method ?Upvotes: 0
Views: 52
Reputation: 11250
It's called anonymous classes and are commonly used to give interface implementation to a method when its called, without creating a separate class that implement the interface for later instantiate it.
In this case the method setOnItemClickListener
receive an instance of interface OnItemClickListener
, we can create a separate class that implement that interface and to later instantiate or just provide to the method an anonymous implementation at the moment of calling.
You can find more detail Anonymous Classes
Upvotes: 3