Java Reference
In-Depth Information
the Shrink button
Similarly, you can add the code for the Shrink button to display a smaller circle when the
Shrink button is clicked.
16.3
Why must a listener be an instance of an appropriate listener interface? Explain how
to register a listener object and how to implement a listener interface.
Check
Point
16.4
Can a source have multiple listeners? Can a listener listen to multiple sources? Can a
source be a listener for itself?
16.5
How do you implement a method defined in the listener interface? Do you need to
implement all the methods defined in the listener interface?
16.6
What method do you use to get the timestamp for an action event?
16.4 Inner Classes
An inner class , or nested class, is a class defined within the scope of another class.
Inner classes are useful for defining listener classes.
Key
Point
We now introduce inner classes in this section and anonymous inner classes in the next sec-
tion and use them to define listener classes. First let us see the code in Figure 16.9. The code
in Figure 16.9a defines two separate classes, Test and A . The code in Figure 16.9b defines A
as an inner class in Test .
public class Test {
...
// OuterClass.java: inner class demo
public class OuterClass {
private int data;
/** A method in the outer class */
public void m() {
// Do something
}
public class A {
...
}
}
// An inner class
class InnerClass {
/** A method in the inner class */
public void mi() {
// Directly reference data and method
// defined in its outer class
(a)
public class Test {
...
data++;
// Inner class
public class A {
m();
}
...
}
}
}
}
(b)
(c)
F IGURE 16.9
Inner classes combine dependent classes into the primary class.
The class InnerClass defined inside OuterClass in Figure 16.9c is another example of
an inner class. An inner class may be used just like a regular class. Normally, you define a class
as an inner class if it is used only by its outer class. An inner class has the following features:
An inner class is compiled into a class named
OuterClassName$InnerClassName.class . For example, the inner class A in
Test is compiled into Test$A.class in Figure 16.9b .
An inner class can reference the data and methods defined in the outer class in which it
nests, so you need not pass the reference of an object of the outer class to the constructor
of the inner class. For this reason, inner classes can make programs simple and concise.
 
 
Search WWH ::




Custom Search