- 6.1. Interfaces
- 6.2. Lambda Expressions
- 6.3. Inner Classes
- 6.4. Service Loaders
- 6.5. Proxies
6.3. Inner Classes
An inner class is a class that is defined inside another class. Why would you want to do that? There are two reasons:
Inner classes can be hidden from other classes in the same package.
Inner class methods can access the data from the scope in which they are defined—including the data that would otherwise be private.
Inner classes used to be very important for concisely implementing callbacks, but nowadays lambda expressions do a much better job. Still, inner classes can be very useful for structuring your code. The following sections walk you through all the details.
6.3.1. Use of an Inner Class to Access Object State
The syntax for inner classes is rather complex. For that reason, I present a simple but somewhat artificial example to demonstrate the use of inner classes. Let's refactor the TimerTest example and extract a TalkingClock class. The constructor for a talking clock has two parameters: the interval between announcements and a flag to turn beeps on or off.
public class TalkingClock { private int interval; private boolean beep; public TalkingClock(int interval, boolean beep) { . . . } public void start() { . . . } public class TimePrinter implements ActionListener // an inner class { . . . } }
Note that the TimePrinter class is now located inside the TalkingClock class. This does not mean that every TalkingClock has a TimePrinter instance field. As you will see, the TimePrinter objects are constructed by methods of the TalkingClock class.
Here is the TimePrinter class in greater detail. Note that the actionPerformed method checks the beep flag before emitting a beep.
public class TimePrinter implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("At the tone, the time is " + Instant.ofEpochMilli(event.getWhen())); if (beep) Toolkit.getDefaultToolkit().beep(); } }
Something surprising is going on. The TimePrinter class has no instance field or variable named beep. Instead, beep refers to the field of the TalkingClock object that created this TimePrinter. As you can see, an inner class method gets to access both its own instance fields and those of the outer object creating it.
For this to work, an object of an inner class always gets an implicit reference to the object that created it (see Figure 6.3).
![Figure 6.3](/content/images/chap6_9780135328378/elementLinks/06_03.jpg)
Figure 6.3: An inner class object has a reference to an outer class object.
This reference is invisible in the definition of the inner class. However, to illuminate the concept, let us call the reference to the outer object outer. Then the actionPerformed method is equivalent to the following:
public void actionPerformed(ActionEvent event) { System.out.println("At the tone, the time is " + Instant.ofEpochMilli(event.getWhen())); if (outer.beep) Toolkit.getDefaultToolkit().beep(); }
The outer class reference is set in the constructor. The compiler modifies all inner class constructors, adding a parameter for the outer class reference. The TimePrinter class defines no constructors; therefore, the compiler synthesizes a no-argument constructor, generating code like this:
public TimePrinter(TalkingClock clock) // automatically generated code { outer = clock; }
Again, please note that outer is not a Java keyword. We just use it to illustrate the mechanism involved in an inner class.
When a TimePrinter object is constructed in the start method, the compiler passes the this reference to the current talking clock into the constructor:
var listener = new TimePrinter(this); // parameter automatically added
Listing 6.7 shows the complete program that tests the inner class. Have another look at the access control. Had the TimePrinter class been a regular class, it would have needed to access the beep flag through a public method of the TalkingClock class. Using an inner class is an improvement. There is no need to provide accessors that are of interest only to one other class.
Listing 6.7 innerClass/InnerClassTest.java
1 package innerClass; 2 3 import java.awt.*; 4 import java.awt.event.*; 5 import java.time.*; 6 7 import javax.swing.*; 8 9 /** 10 * This program demonstrates the use of inner classes. 11 * @version 1.11 2017-12-14 12 * @author Cay Horstmann 13 */ 14 public class InnerClassTest 15 { 16 public static void main(String[] args) 17 { 18 var clock = new TalkingClock(1000, true); 19 clock.start(); 20 21 // keep program running until the user selects "OK" 22 JOptionPane.showMessageDialog(null, "Quit program?"); 23 System.exit(0); 24 } 25 } 26 27 /** 28 * A clock that prints the time in regular intervals. 29 */ 30 class TalkingClock 31 { 32 private int interval; 33 private boolean beep; 34 35 /** 36 * Constructs a talking clock. 37 * @param interval the interval between messages (in milliseconds) 38 * @param beep true if the clock should beep 39 */ 40 public TalkingClock(int interval, boolean beep) 41 { 42 this.interval = interval; 43 this.beep = beep; 44 } 45 46 /** 47 * Starts the clock. 48 */ 49 public void start() 50 { 51 var listener = new TimePrinter(); 52 var timer = new Timer(interval, listener); 53 timer.start(); 54 } 55 56 public class TimePrinter implements ActionListener 57 { 58 public void actionPerformed(ActionEvent event) 59 { 60 System.out.println("At the tone, the time is " 61 + Instant.ofEpochMilli(event.getWhen())); 62 if (beep) Toolkit.getDefaultToolkit().beep(); 63 } 64 } 65 }
6.3.2. Special Syntax Rules for Inner Classes
In the preceding section, we explained the outer class reference of an inner class by calling it outer. Actually, the proper syntax for the outer reference is a bit more complex. The expression
OuterClass.this
denotes the outer class reference. For example, you can write the actionPerformed method of the TimePrinter inner class as
public void actionPerformed(ActionEvent event) { . . . if (TalkingClock.this.beep) Toolkit.getDefaultToolkit().beep(); }
Conversely, you can write the inner object constructor more explicitly, using the syntax
outerObject.new InnerClass(construction arguments)
For example:
ActionListener listener = this.new TimePrinter();
Here, the outer class reference of the newly constructed TimePrinter object is set to the this reference of the method that creates the inner class object. This is the most common case. As always, the this. qualifier is redundant. However, it is also possible to set the outer class reference to another object by explicitly naming it. For example, since TimePrinter is a public inner class, you can construct a TimePrinter for any talking clock:
var jabberer = new TalkingClock(1000, true); TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
Note that you refer to an inner class as
OuterClass.InnerClass
when it occurs outside the scope of the outer class.
6.3.3. Are Inner Classes Useful? Actually Necessary? Secure?
When inner classes were added to the Java language in Java 1.1, many programmers considered them a major new feature that was out of character with the Java philosophy of being simpler than C++. The inner class syntax is undeniably complex. (It gets more complex as we study anonymous inner classes later in this chapter.) It is not obvious how inner classes interact with other features of the language, such as access control and security.
Inner classes are translated into regular class files with $ (dollar signs) separating the outer and inner class names. For example, the TimePrinter class inside the TalkingClock class is translated to a class file TalkingClock$TimePrinter.class. To see this at work, try the following experiment: run the ReflectionTest program of Chapter 5, and give it the class TalkingClock$TimePrinter to reflect upon. Alternatively, simply use the javap utility:
javap -private ClassName
You will get the following printout:
public class innerClass.TalkingClock$TimePrinter implements java.awt.event.ActionListener { final innerClass.TalkingClock this$0; public innerClass.TalkingClock$TimePrinter(innerClass.TalkingClock); public void actionPerformed(java.awt.event.ActionEvent); }
You can plainly see that the compiler has generated an additional instance field, this$0, for the reference to the outer class. (The name this$0 is synthesized by the compiler—you cannot refer to it in your code.) You can also see the TalkingClock parameter for the constructor.
If the compiler can automatically do this transformation, couldn’t you simply program the same mechanism by hand? Let’s try it. We would make TimePrinter a regular class, outside the TalkingClock class. When constructing a TimePrinter object, we pass it the this reference of the object that is creating it.
class TalkingClock { . . . public void start() { var listener = new TimePrinter(this); var timer = new Timer(interval, listener); timer.start(); } } class TimePrinter implements ActionListener { private TalkingClock outer; . . . public TimePrinter(TalkingClock clock) { outer = clock; } }
Now let us look at the actionPerformed method. It needs to access outer.beep.
if (outer.beep) . . . // ERROR
Here we run into a problem. The inner class can access the private data of the outer class, but our external TimePrinter class cannot.
Thus, inner classes are genuinely more powerful than regular classes because they have more access privileges.
6.3.4. Local Inner Classes
If you look carefully at the code of the TalkingClock example, you will find that you need the name of the type TimePrinter only once: when you create an object of that type in the start method.
In a situation like this, you can define the class locally in a single method.
public void start() { class TimePrinter implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("At the tone, the time is " + Instant.ofEpochMilli(event.getWhen())); if (beep) Toolkit.getDefaultToolkit().beep(); } } var listener = new TimePrinter(); var timer = new Timer(interval, listener); timer.start(); }
Local classes are never declared with an access specifier (that is, public or private). Their scope is always restricted to the block in which they are declared.
Local classes have one great advantage: They are completely hidden from the outside world—not even other code in the TalkingClock class can access them. No method except start has any knowledge of the TimePrinter class.
6.3.5. Accessing Variables from Outer Methods
Local classes have another advantage over other inner classes. Not only can they access the fields of their outer classes; they can even access local variables! However, those local variables must be effectively final. That means, they may never change once they have been assigned.
Here is a typical example. Let’s move the interval and beep parameters from the TalkingClock constructor to the start method.
public void start(int interval, boolean beep) { class TimePrinter implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("At the tone, the time is " + Instant.ofEpochMilli(event.getWhen())); if (beep) Toolkit.getDefaultToolkit().beep(); } } var listener = new TimePrinter(); var timer = new Timer(interval, listener); timer.start(); }
Note that the TalkingClock class no longer needs to store a beep instance field. It simply refers to the beep parameter variable of the start method.
Maybe this should not be so surprising. The line
if (beep) . . .
is, after all, ultimately inside the start method, so why shouldn’t it have access to the value of the beep variable?
To see why there is a subtle issue here, let’s consider the flow of control more closely.
The start method is called.
The object variable listener is initialized by a call to the constructor of the inner class TimePrinter.
The listener reference is passed to the Timer constructor, the timer is started, and the start method exits. At this point, the beep parameter variable of the start method no longer exists.
A second later, the actionPerformed method executes if (beep) . . .
For the code in the actionPerformed method to work, the TimePrinter class must have copied the beep field as a local variable of the start method, before the beep parameter value went away. That is indeed exactly what happens. In our example, the compiler synthesizes the name TalkingClock$1TimePrinter for the local inner class. If you use the ReflectionTest program or the javap utility again to spy on the TalkingClock$1TimePrinter class, you will get the following output:
class TalkingClock$1TimePrinter { TalkingClock$1TimePrinter(); public void actionPerformed(java.awt.event.ActionEvent); final boolean val$beep; final TalkingClock this$0; }
When an object is created, the current value of the beep variable is stored in the val$beep field. As of Java 11, this happens with “nest mate” access. Previously, the inner class constructor had an additional parameter to set the field. Either way, the inner class field persists even if the local variable goes out of scope.
6.3.6. Anonymous Inner Classes
When using local inner classes, you can often go a step further. If you want to make only a single object of this class, you don’t even need to give the class a name. Such a class is called an anonymous inner class.
public void start(int interval, boolean beep) { var listener = new ActionListener() { public void actionPerformed(ActionEvent event) { System.out.println("At the tone, the time is " + Instant.ofEpochMilli(event.getWhen())); if (beep) Toolkit.getDefaultToolkit().beep(); } }; var timer = new Timer(interval, listener); timer.start(); }
This syntax is very cryptic indeed. What it means is this: Create a new object of a class that implements the ActionListener interface, where the required method actionPerformed is the one defined inside the braces { }.
In general, the syntax is
new SuperType(construction arguments) { inner class methods and data }
Here, SuperType can be an interface, such as ActionListener; then, the inner class implements that interface. SuperType can also be a class; then, the inner class extends that class.
An anonymous inner class cannot have constructors because the name of a constructor must be the same as the name of a class, and the class has no name. Instead, the construction arguments are given to the superclass constructor. In particular, whenever an inner class implements an interface, it cannot have any construction arguments. Nevertheless, you must supply a set of parentheses as in
new InterfaceType() { methods and data }
You have to look carefully to see the difference between the construction of a new object of a class and the construction of an object of an anonymous inner class extending that class.
var queen = new Person("Mary"); // a Person object var count = new Person("Dracula") { . . . }; // an object of an inner class extending Person
If the closing parenthesis of the construction argument list is followed by an opening brace, then an anonymous inner class is being defined.
Listing 6.8 contains the complete source code for the talking clock program with an anonymous inner class. If you compare this program with Listing 6.7, you will see that in this case, the solution with the anonymous inner class is quite a bit shorter and, hopefully, with some practice, as easy to comprehend.
For many years, Java programmers routinely used anonymous inner classes for event listeners and other callbacks. Nowadays, you are better off using a lambda expression. For example, the start method from the beginning of this section can be written much more concisely with a lambda expression like this:
public void start(int interval, boolean beep) { var timer = new Timer(interval, event -> { System.out.println( "At the tone, the time is " + Instant.ofEpochMilli(event.getWhen())); if (beep) Toolkit.getDefaultToolkit().beep(); }); timer.start(); }
Listing 6.8 anonymousInnerClass/AnonymousInnerClassTest.java
1 package anonymousInnerClass; 2 3 import java.awt.*; 4 import java.awt.event.*; 5 import java.time.*; 6 7 import javax.swing.*; 8 9 /** 10 * This program demonstrates anonymous inner classes. 11 * @version 1.12 2017-12-14 12 * @author Cay Horstmann 13 */ 14 public class AnonymousInnerClassTest 15 { 16 public static void main(String[] args) 17 { 18 var clock = new TalkingClock(); 19 clock.start(1000, true); 20 21 // keep program running until the user selects "OK" 22 JOptionPane.showMessageDialog(null, "Quit program?"); 23 System.exit(0); 24 } 25 } 26 27 /** 28 * A clock that prints the time in regular intervals. 29 */ 30 class TalkingClock 31 { 32 /** 33 * Starts the clock. 34 * @param interval the interval between messages (in milliseconds) 35 * @param beep true if the clock should beep 36 */ 37 public void start(int interval, boolean beep) 38 { 39 var listener = new ActionListener() 40 { 41 public void actionPerformed(ActionEvent event) 42 { 43 System.out.println("At the tone, the time is " 44 + Instant.ofEpochMilli(event.getWhen())); 45 if (beep) Toolkit.getDefaultToolkit().beep(); 46 } 47 }; 48 var timer = new Timer(interval, listener); 49 timer.start(); 50 } 51 }
6.3.7. Static Classes
Occasionally, you may want to nest one class inside another, but you don’t need the nested class to have a reference to the outer class object. You can suppress the generation of that reference by declaring the nested class static.
The Java Language Specification uses the term “nested class” for any class that is declared inside another class or interface, “static class” for a (necessarily nested) static class, and “inner class” for a nested class that is not static.
Here is a typical example of where you would want to do this. In an ArrayAlg class, we have a task that finds a range of elements of an array. Then you need to return the start and the end of the range. We can achieve that by defining a class Range that holds two values:
class Range { private int from; private int to; public Range(int from) { . . . } public void extend() { . . . } . . . }
Of course, Range is an exceedingly common name, and in a large project, it is quite possible that some other programmer had the same bright idea and defined another Range class in the same package. We can solve this potential name clash by making Range a public inner class inside ArrayAlg. Then the class will be known to the public as ArrayAlg.Range:
ArrayAlg.Range r = ArrayAlg.longestRun(numbers);
However, unlike the inner classes used in previous examples, we do not want to have a reference to any other object inside a Range object. That reference can be suppressed by declaring the nested class static:
class ArrayAlg { public static class Range { . . . } . . . }
A static class is exactly like an inner class, except that an object of a static class does not have a reference to the outer class object that generated it. In our example, we must use a static class because the nested class instance is constructed inside a static method:
public static Pair longestRun(double[] values) { . . . Range current = new Range(. . .); . . . if (. . .) longest = current; . . . return longest; }
Had the Range class not been declared as static, the compiler would have flagged the constructor call as an error. After all, there is no implicit object of type ArrayAlg available to initialize the inner class instance.
You should use a static class whenever a nested class does not need to access an outer class object.
Here, I purposefully made the Range class mutable. It might be better to make the Range class immutable, and to declare it as a record. A record is automatically static.
Listing 6.9 contains the complete source code of the ArrayAlg class and the nested Pair class.
Listing 6.9 staticInnerClass/StaticInnerClassTest.java
1 package staticInnerClass; 2 3 /** 4 * This program demonstrates the use of static inner classes. 5 * @version 1.1 2023-12-19 6 * @author Cay Horstmann 7 */ 8 public class StaticInnerClassTest 9 { 10 public static void main(String[] args) 11 { 12 double[] numbers = { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6 }; 13 ArrayAlg.Range r = ArrayAlg.longestRun(numbers); 14 System.out.println("from = " + r.getFrom()); 15 System.out.println("to = " + r.getTo()); 16 } 17 } 18 19 class ArrayAlg 20 { 21 /** 22 * A range of index values. 23 */ 24 public static class Range 25 { 26 private int from; 27 private int to; 28 29 /** 30 * Constructs a range of length 1. 31 * @param from the initial index value of this range 32 */ 33 public Range(int from) 34 { 35 this.from = from; 36 this.to = from + 1; 37 } 38 39 /** 40 * Extends this range by one element. 41 */ 42 public void extend() 43 { 44 this.to++; 45 } 46 47 /** 48 * Gets the starting index value of this range. 49 * @return the starting index 50 */ 51 public int getFrom() 52 { 53 return from; 54 } 55 56 /** 57 * Gets the first index past the end of this range. 58 * @return the past-the-end index 59 */ 60 public int getTo() 61 { 62 return to; 63 } 64 65 /** 66 * Returns the number of elements in this range. 67 * @return the number of elements 68 */ 69 public int length() 70 { 71 return to - from; 72 } 73 } 74 75 /** 76 * A "run" is a sequence of repeating adjacent elements. For example, in the array 77 * 1 2 3 3 3 4 4, the runs are (trivially) 1 and 2, and 3 3 3 3 and 4 4. 78 * Returns the range of the longest run. 79 * @param values an array of length at least 1 80 * @return the range of the longest run 81 */ 82 public static Range longestRun(double[] values) 83 { 84 Range longest = new Range(0); 85 Range current = new Range(0); 86 for (int i = 1; i < values.length; i++) 87 { 88 if (values[i] == values[i - 1]) current.extend(); 89 else 90 { 91 if (longest.length() < current.length()) longest = current; 92 current = new Range(i); 93 } 94 } 95 if (longest.length() < current.length()) longest = current; 96 return longest; 97 } 98 }