By Barry Burd

Here’s big news! You can define a class inside another class! This is handy for Android app developers. Most classes don’t live inside another class, and most classes don’t contain other classes. But when the idea behind one class screams out to be part of another class, feel free to create a class within a class.

Named inner classes

In this code, the MyActivity class contains its own MyListener class.

package com.allmycode.samples;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MyActivity extends Activity {
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = ((Button) findViewById(R.id.button1));
button.setOnClickListener(new MyListener());
}
class MyListener implements OnClickListener {
@Override
public void onClick(View arg0) {
button.setBackgroundColor
(android.graphics.Color.GRAY);
}
}
}

The MyListener class is an inner class. An inner class is a lot like any other class. But within an inner class’s code, you can refer to the enclosing class’s fields. For example, the onClick method inside MyListener uses the name button, and button is defined in the enclosing MyActivity class.

Anonymous inner classes

Notice that the code above uses the MyListener class only once. (The only use is in a call to button.setOnClickListener.) So, do you really need a name for something that’s used only once? No, you don’t. You can substitute the entire definition of the inner class inside the call to button.setOnClickListener. When you do this, you have an anonymous inner class. The following code shows you how it works.

package com.allmycode.samples;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MyActivity extends Activity {
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = ((Button) findViewById(R.id.button1));
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
button.setBackgroundColor
(android.graphics.Color.GRAY);
}
});
}
}

Inner classes are good for things like event handlers, such as the onClick method. The most difficult thing about an anonymous inner class is keeping track of the parentheses, the curly braces, and the indentation. So here’s some advice: Start by writing code without any inner classes. Later, when you become bored with ordinary Java classes, experiment by changing some of your ordinary classes into inner classes.