Inner Classes Core Java

An inner class is a class that is defined inside another class. Why would you want to do that? There are three reasons:

  • Inner class methods can access the data from the scope in which they are defined— including data that would otherwise be private.
  • Inner classes can be hidden from other classes in the same package.
  • Anonymous inner classes are handy when you want to define callbacks without writing a lot of code.

We will break up this rather complex topic into several steps.

  • you will see a simple inner class that accesses an instance field of its outer class.
  • we peek inside inner classes to see how they are translated into regular classes. Squeamish readers may want to skip that section.
  • we discuss local inner classes that can access local variables of the enclosing scope.
  • we introduce anonymous inner classes and show how they are commonly used to implement callbacks.
  • you will see how static inner classes can be used for nested helper classes.

C++ NOTE: C++ has nested classes. A nested class is contained inside the scope of the enclosing class. Here is a typical example: a linked list class defines a class to hold the links, and a class to define an iterator position.

The nesting is a relationship between classes, not objects. A LinkedList object does not have subobjects of type Iterator or Link.

There are two benefits: name control and access control. Because the name Iterator is nested inside the LinkedList class, it is externally known as LinkedList::Iterator and cannot conflict with another class called Iterator. In Java, this benefit is not as important because Java packages give the same kind of name control. Note that the Link class is in the privatepart of the LinkedList class. It is completely hidden from all other code. For that reason, it is safe to make its data fields public. They can be accessed by the methods of the LinkedListclass (which has a legitimate need to access them), and they are not visible elsewhere. In Java, this kind of control was not possible until inner classes were introduced.

However, the Java inner classes have an additional feature that makes them richer and moreuseful than nested classes in C++. An object that comes from an inner class has an implicit referenceto the outer class object that instantiated it. Through this pointer, it gains access to the total state of the outer object.

In Java, static inner classes do not have this added pointer. They are the Java analog to nested classes in C++.

Use of an Inner Class to Access Object State

The syntax for inner classes is rather complex. For that reason, we use a simple but somewhat artificial example to demonstrate the use of inner classes. We refactor the

TimerTest example and extract a Talking Clock class. A talking clock is constructed with two parameters: the interval between announcements and a flag to turn beeps on or off.

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 TimePrinterobjects are constructed by methods of the Talking Clock class.

Here is the Time Printer class in greater detail. Note that the action Performed method checks the beep flag before emitting a beep. private class TimePrinter implements ActionListener

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 Time-Printer. This is quite innovative. Traditionally, a method could refer to the data fields of the object invoking the method. An inner class method gets to access both its own data 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.

An inner class object has a reference to an outer class object

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:

The outer class reference is set in the constructor. The compiler modifies all inner class constructors, adding a parameter for the outer class reference. Because the TimePrinterclass defines no constructors, the compiler synthesizes a default constructor, generating code like this:

Again, please note, 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:

Listing below shows the complete program that tests the inner class. Have another look at the access control. Had the TimePrinter class been a regular class, then 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.

NOTE: We could have declared the TimePrinter class as private. Then only TalkingClock methods would be able to construct TimePrinter objects. Only inner classes can be private.Regular classes always have either package or public visibility.

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

Conversely, you can write the inner object constructor more explicitly, using the syntax outer Inner Class(construction parameters) For example:

Here, the outer class reference of the newly constructed Time Printer 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, because TimePrinteris a public inner class, you can construct a TimePrinter for any talking clock:

Note that you refer to an inner class as

when it occurs outside the scope of the outer class.

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 controland security.

By adding a feature that was elegant and interesting rather than needed, has Java started down the road to ruin that has afflicted so many other languages?

While we won’t try to answer this question completely, it is worth noting that inner classes are a phenomenon of the compiler, not the virtual machine. Inner classes aretranslated into regular class files with $ (dollar signs) delimiting outer and inner class names, and the virtual machine does not have any special knowledge about them.

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 , and give it the class Talking Clock $Time Printer to reflect upon. Alternatively, simply use the javap utility:

NOTE: If you use UNIX, remember to escape the $ character if you supply the class name on the command line. That is, run the ReflectionTest or javap program as java Reflection Test Talking Clock $Time Printer or-private Talking Clock $Time Printer

You will get the following printout:

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.

Now let us look at the actionPerformed method. It needs to access outer.beep.

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.

You may well wonder how inner classes manage to acquire those added access privileges, because inner classes are translated to regular classes with funny names —the virtual machine knows nothing at all about them. To solve this mystery, let’s again use the Reflection Test program to spy on the TalkingClock class:

Notice the static access$0 method that the compiler added to the outer class. It returns the beep field of the object that is passed as a parameter.

The inner class methods call that method. The statement

in the actionPerformed method of the TimePrinter class effectively makes the following call:

Is this a security risk? You bet it is. It is an easy matter for someone else to invoke the access$0 method to read the private beep field. Of course, access$0 is not a legal name for a Java method. However, hackers who are familiar with the structure of class files can easily produce a class file with virtual machine instructions to call that method, for example, by using a hex editor. Because the secret access methods have package visibility, the attack code would need to be placed inside the same package as the class under attack.

To summarize, if an inner class accesses a private data field, then it is possible to access that data field through other classes that are added to the package of the outer class, but to do so requires skill and determination. A programmer cannot accidentally obtain access but must intentionally build or modify a class file for that purpose.

NOTE: The synthesized constructors and methods can get quite convoluted. (Skip this note if you are squeamish.) Suppose we turn TimePrinter into a private inner class. There are no private classes in the virtual machine, so the compiler produces the next best thing, a package- visible class with a private constructor

Of course, nobody can call that constructor, so there is a second package-visible constructor Talking Clock $Time Printer (Talking Clock, Talking Clock$1); that calls the first one.

The complier translates the constructor call in the start method of the TalkingClock class to new Talking Clock $Time Printer(this, null)

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. When you have a situation like this, you can define the class locally in a single method.

Local classes are never declared with an access specifier (that is, public or private). Theirscope is always restricted to the block in which they

are declared.

Local classes have a great advantage: they are completely hidden from the outsideworld —not even other code in the Talking Clock class can access them. No method exceptstart has any knowledge of the TimePrinter class.

Accessing final Variables from Outer Methods

Local classes have another advantage over other inner classes. Not only can they accessthe fields of their outer classes, they can even access local variables! However, thoselocal variables must be declared final. Here is a typical example. Let’s move the intervaland beep parameters from the TalkingClock constructor to the start method.public void start(int interval, final boolean beep)

Note that the TalkingClock class no longer needs to store a beep instance field. It simplyrefers to the beep parameter variable of the start method. Maybe this should not be so surprising. The line

is, after all, ultimately inside the start method, so why shouldn’t it have access to thevalue of the beep variable?

To see why there is a subtle issue here, let’s consider the flow of control more closely.

  1. The start method is called.
  2. The object variable listener is initialized by a call to the constructor of the inner class TimePrinter.
  3. The listener reference is passed to the Timer constructor, the timer is started, and thestart method exits. At this point, the beep parameter variable of the start method nolonger exists.
  4. A second later, the actionPerformed method executes if (beep) . . . .

For the code in the actionPerformed method to work, the TimePrinter class must havecopied the beep field, as a local variable of the start method, before the beep parametervalue went away. That is indeed exactly what happens. In our example, the compilersynthesizes the name Talking Clock$1 Time Printer for the local inner class. If you use the Reflection Test program again to spy on the Talking Clock $1Time Printer class, you get the following output:

Note the boolean parameter to the constructor and the val$beep instance variable. When anobject is created, the value beep is passed into the constructor and stored in the val$beepfield. The compiler detects access of local variables, makes matching instance fields foreach one of them, and copies the local variables into the constructor so that the instancefields can be initialized.

From the programmer’s point of view, local variable access is quite pleasant. It makesyour inner classes simpler by reducing the instance fields that you need to programexplicitly.

As we already mentioned, the methods of a local class can refer only to local variablesthat are declared final. For that reason, the beep parameter was declared final in ourexample. A local variable that is declared final cannot be modified after it has been initialized.Thus, it is guaranteed that the local variable and the copy that is made inside the local class always have the same value.

NOTE: You have seen final variables used for constants, such as

The final keyword can be applied to local variables, instance variables, and static variables.In all cases it means the same thing: You can assign to this variable once after it has beencreated. Afterwards, you cannot change the value—it is final.

However, you don’t have to initialize a final variable when you define it. For example, thefinal parameter variable beep is initialized once after its creation, when the start method iscalled. (If the method is called multiple times, each call has its own newly created beep parameter.) The val$beep instance variable that you can see in the TalkingClock$1TimePrinterinner class is set once, in the inner class constructor. A final variable that isn’t initializedwhen it is defined is often called a blank final variable.

The final restriction is somewhat inconvenient. Suppose, for example, you want toupdate a counter in the enclosing scope. Here, we want to count how often the compareTomethod is called during sorting.

You can’t declare counter as final because you clearly need to update it. You can’t replace it with an Integer because Integer objects are immutable. The remedy is to use an array of length 1:

(The array variable is still declared as final, but that merely means that you can’t have it refer to a different array. You are free to mutate the array elements.)

When inner classes were first invented, the prototype compiler automatically made this transformation for all local variables that were modified in the inner class. However, some programmers were fearful of having the compiler produce heap objects behind their backs, and the final restriction was adopted instead. It is possible that a future versionof the Java language will revise this decision.

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.

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 action Performed is the one defined inside the braces { }.

In general, the syntax is

Here, SuperType can be an interface, such as ActionListener; then, the inner class implementsthat interface. Or SuperType can 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 parameters are given to the superclass constructor. In particular, whenever an inner class implements an interface, it cannot have any construction parameters. Nevertheless, you must supply a set of parentheses as in

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.

If the closing parenthesis of the construction parameter list is followed by an opening brace, then an anonymous inner class is being defined.

Are anonymous inner classes a great idea or are they a great way of writing obfuscated code? Probably a bit of both. When the code for an inner class is short, just a few lines of simple code, then anonymous inner classes can save typing time, but it is exactly timesaving features like this that lead you down the slippery slope to “Obfuscated Java Code Contests.”

Listing below contains the complete source code for the talking clock program with an anonymous inner class. If you compare this program with Listing, you will find that in this case the solution with the anonymous inner class is quite a bit shorter, and, hopefully, with a bit of practice, as easy to comprehend.

Static Inner Classes

Occasionally, you want to use an inner class simply to hide one class inside another, but you don’t need the inner class to have a reference to the outer class object. You can suppress the generation of that reference by declaring the inner class static.

Here is a typical example of where you would want to do this. Consider the task of computing the minimum and maximum value in an array. Of course, you write one method to compute the minimum and another method to compute the maximum.

When you call both methods, then the array is traversed twice. It would be more efficient to traverse the array only once, computing both the minimum and the maximum simultaneously.

However, the method must return two numbers. We can achieve that by defining a class
Pair that holds two values:

The minmax function can then return an object of type Pair.

The caller of the function uses the getFirst and getSecond methods to retrieve the answers:

Of course, the name Pair is an exceedingly common name, and in a large project, it is quite possible that some other programmer had the same bright idea, except that the other programmer made a Pair class that contains a pair of strings. We can solve this potential name clash by making Pair a public inner class inside ArrayAlg. Then the class will be known to the public as ArrayAlg.Pair:

However, unlike the inner classes that we used in previous examples, we do not want tohave a reference to any other object inside a Pair object. That reference can be suppressed by declaring the inner class static:

Of course, only inner classes can be declared static. A static inner class is exactly like any other inner class, except that an object of a static inner class does not have a reference to the outer class object that generated it. In our example, we must use a static inner class because the inner class object is constructed inside a static method:

Had the Pair class not been declared as static, the compiler would have complained that there was no implicit object of type ArrayAlg available

to initialize the inner class object.

NOTE: You use a static inner class whenever the inner class does not need to access an outer class object. Some programmers use the term nested class to describe static innerclasses.

NOTE: Inner classes that are declared inside an interface are automatically static andpublic.

Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Core Java Topics