0

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 .

4

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.

  • The anonymous class overrides the onItemClick method of OnItemClickListener. That means the anonymous class is extending OnItemClickListener. Why there is no extends keyword ? – Tulains Córdova Oct 21 '14 at 12:10
  • 1
    If OnItemClickListner is a class, the anonymous class extends it automatically. If it is a interface, the anonymous class implements it. You don't need to do this explicitly. Also, in order to use the extends keyword, you need to specify a name for the sub-class: MyOnItemClickListener extends OnItemClickListener. Since an anonymous class has no name, you cannot use extends (or implements). – Phil Oct 21 '14 at 12:54
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.