Java Reference
In-Depth Information
Beginning Java 8
Scripting in Java
The fact that the scope of a local inner class is limited to its enclosing block has some implications on how to
declare a local inner class. Consider the following class declaration:
package com.jdojo.innerclasses;
public class SomeTopLevelClass {
// Some code for SomeTopLevelClass goes here
public void someMethod() {
class SomeLocalInnerClass {
// Some code for SomeLocalInnerClass goes here
}
// SomeLocalInnerClass can only be used here
}
}
SomeTopLevelClass
is a top-level class. The
someMethod()
method of
SomeTopLevelClass
declares the
SomeLocalInnerClass
local inner class. Note that the name of the local inner class,
SomeLocalInnerClass
, can only
be used inside the
someMethod()
method. This implies that objects of the
SomeLocalInnerClass
can only be created
and used inside the
someMethod()
method. This limits the use of a local inner class to only being used inside its
enclosing block—in your case the
someMethod()
method. At this point, it may seem that a local inner class is not
very useful. However, Listing 2-4 demonstrated that the code for the local inner class
TitleIterator
can be called
from another class,
TitleListTest
. This was possible because the local inner class
TitleIterator
implemented the
Iterator
interface.
To use a local inner class outside its enclosing block, the local inner class must do one or both of the following:
•
Implement a public interface
•
Inherit from another public class and override some of its superclass methods
The name of the interface or another class must be available outside the enclosing block that defines the local
inner class. Listing 2-3 and Listing 2-4 illustrate the first case where a local inner class implements an interface.
Listing 2-5 and Listing 2-6 illustrate the second case, where a local inner class inherits from another public class.
Listing 2-7 provides a test class to test a local inner class. The example is trivial. However, it illustrates the concept
of how to use a local inner class by inheriting it from another class. Note that you may get a different output when
you run the program in Listing 2-7.
Listing 2-5.
Declaring a Top-Level Class, Which Is Used as the Superclass for a Local Class
// RandomInteger.java
package com.jdojo.innerclasses;
import java.util.Random;
public class RandomInteger {
protected Random rand = new Random();