MY mENU


Saturday, 11 February 2012

Anonymous Inner Class in Java


 Anonymous Inner Classes:

Android uses anonymous inner classes to great effect. Anonymous inner classes are basically developer shorthand, allowing the developer to create, define, and use a custom object all in one “line.” You may have seen examples of the use of anonymous inner class in sample code and not even realized it.
To create an anonymous inner class, you only provide the right-hand side of the definition. Begin with the new keyword, followed by the class or interface you wish to extend or implement, followed by the class definition. This will create the class and return it as a value which you can then use to call a method.
When we use an anonymous inner class, the object created does not get assigned a name (thus the term anonymous). The side effect, of course, is that the object is used used just once. For example, it’s common to use an anonymous inner class to construct a custom version of an object as a return value. For example, here we extend the Truck class (assuming its defined elsewhere and has a field called mpg and two methods, start() and stop():
  1. Truck getTruck()  
  2. {  
  3.     return new Truck()  
  4.     {  
  5.         int mpg = 3;  
  6.         void start() { /* start implementation */ }  
  7.         void stop() { /* stop implementation */ }  
  8.     };  
  9. }  
Now let’s look at practical examples of anonymous inner classes used in Android.

Using an Anonymous Inner Class to Define a Listener:

Android developers often use anonymous inner classes to define specialized listeners, which register callbacks for specific behavior when an event occurs. For example, to listen for clicks on a View control, the developer must call the setOnClickListener() method, which takes a single parameter: a View.OnClickListener object.
Developers routinely use the anonymous inner class technique to create, define and use their custom View.OnClickListener, as follows:
  1. Button aButton = (Button) findViewById(R.id.MyButton);  
  2. aButton.setOnClickListener(new View.OnClickListener() {  
  3.             public void onClick(View v) {  
  4.                 // User clicked my button, do something here!  
  5.             }  
  6. });  

Using an Anonymous Inner Class to Start a Thread:

Let’s look at another example. It’s quite common to define a new Thread class, provide the implementation of its run() method, and start that thread, all in one go:
  1. new Thread() {  
  2.     public void run()  
  3.     {  
  4.         doWorkHere();  
  5.     }  
  6. }.start();  

Using a Named Inner Class:

Using anonymous inner classes for listeners in Android is so common that it is practically second nature to do so. Why, then, would you not want to use them? Let’s answer this through a hypothetical example.
Let’s say you have a screen that has 100 buttons on it (we did say hypothetical, right?). Now, let’s say each button, when pressed, does the exact same thing. In this case, we’ll just listen for clicks and Toast the text from the View object passed in (the text shown on the Button that was clicked):
Here’s pseudo code to do that:
  1. Button[] buttons = getAllOneHundredButtonsAsArray();  
  2. for (Button button : buttons) {  
  3.     button.setOnClickListener(new View.OnClickListener() {  
  4.         public void onClick(View v) {  
  5.             showToast(v.getText());  
  6.         }  
  7.     });  
  8. }  
Short and elegant, so what’s wrong with it? At each iteration, a new OnClickListener object is instantiated. Since each one is exactly the same, there is no good reason to create 100 of them. Instead, you can create a single, named, inner class, instantiate it once, then pass that to the setOnClickListener() method. For instance:
  1. class MyActivity extends Activity {  
  2.   
  3.     public void myMethod() {  
  4.        MyClickHandler handler = new MyClickHandler();  
  5.         Button[] buttons = getAllOneHundredButtonsAsArray();  
  6.         for (Button button : buttons) {  
  7.             button.setOnClickListener(handler);  
  8.         }  
  9.     }  
  10.   
  11.     class MyClickHandler implements View.OnClickListener {  
  12.         public void onClick(View v) {  
  13.             showToast(((Button) v).getText());  
  14.         }  
  15.     }  
  16. }  
If you prefer anonymity, you can still assign an anonymous inner class to a variable and use that, like so:
  1. class MyActivity extends Activity {  
  2.   
  3.     public void myMethod() {  
  4.         View.OnClickListener handler = new View.OnClickListener() {  
  5.                 public void onClick(View v) {  
  6.                     showToast(((Button) v).getText());  
  7.                 }  
  8.             };  
  9.   
  10.         Button[] buttons = getAllOneHundredButtonsAsArray();  
  11.         for (Button button : buttons) {  
  12.             button.setOnClickListener(handler);  
  13.         }  
  14.     }  
  15. }  
The method is up to you, but keep in mind the potential memory and performance issues that instantiating a bunch of objects may have.

No comments:

Post a Comment