Java IoT Authors: Zakia Bouachraoui, Pat Romanski, Elizabeth White, Yeshim Deniz, Liz McMillan

Related Topics: Java IoT

Java IoT: Article

Using Inner Classes

Using Inner Classes

In JDK 1.1, no other new feature is likely to have more impact on Java programmers than the less-publicized inner classes feature. It'll change the way in which Java programs have been traditionally written. The primary goal of this feature is to provide the ability to declare classes within classes.

To incorporate the new inner classes syntax and scope rules, a few significant changes were made to the Java language specifications. However, no changes were made to the Java Virtual Machine. This is because the new compiler implements the inner classes syntax using Java 1.0, which has no inner classes. As a result, binary compatibility is still maintained with Java programs written in Java 1.0.

The inner classes syntax is somewhat complicated. This article will provide an informal introduction to the syntax and discuss how inner classes can be used. As a case study, the author converted an existing application to JDK 1.1 using inner classes. This application was originally developed for the article on Image Loading (JDJ Vol 1, Issue 3). See Figure 1.

Need for Inner Classes
You can always write Java programs without using inner classes. So, is this feature really needed?. We'll address this question through an example shown in Listings 1 and 2. Such situations typically occur in GUI programming.

Listing 1 shows a simplified version of code that implements the GUI for the application shown in Figure 1. The outer-most ImageViewer class needs the CommandPanel class to create the GUI. The CommandPanel class needs the DisplayCommand class to handle the dispBtn events. As you can see from the code, the ImageViewer object is passed as an argument to the CommandPanel class and the CommandPanel object is passed as an argument to the DisplayCommand class. This is done in order for the actionPerformed method to invoke the displayImage method in the ImageViewer.

Let's suppose we can declare the CommandPanel class within the ImageViewer class as shown in Listing 2. Similarly, the DisplayCommand class is within the CommandPanel class. The CommandPanel class can then be considered a member of the ImageViewer class. In the same way, the DisplayCommand class can be considered as a member of the CommandPanel class. It is evident from the example that there is no need to pass the calling class as an argument to the called class. Furthermore, by placing the CommandPanel class and the DisplayCommand class close to where they are used, readability is considerably improved.

Using inner classes, we can declare classes within the body of another class just as in Listing 2. Whether it is the handling of events or developing huge applications, inner classes can result in compact Java programs and improved readability.

Furthermore, the lack of pointers in Java is strongly felt in applications that need to employ asynchronous operations such as callbacks. Event handling is a form of callback. A variation of inner class, called anonymous classes, allows the declaration of a class itself to be passed as an argument to a method. For example, the entire body of the DisplayCommand class can be passed as an argument to the addActionListener method. Such capabilities would make the implementation of callbacks simple, concise and elegant.

In order to explain the inner classes syntax and terms, we'll use the contrived example shown in Listing 3. This example has a number of classes, each having at least one method that prints the name of the class.

Nesting of Classes
The inner classes feature allows classes to be nested. A nested class is always surrounded by another class. We'll call such a class the enclosing class. An inner class can have as many enclosing classes as there are levels of nesting. In a package, there will always be classes that do not have an enclosing class. We'll call such classes as top-most1 classes. A top-most class is a member of the package to which it belongs. In the Image Viewer example, the ImageViewer class is the top-most class. Classes defined using JDK 1.0 are all top-most classes and we know from the Java language specifications that such classes cannot be declared static.

The inner classes feature allows a class to be declared as a member of another class. Therefore, a class that is a member of the top-most class can be declared static. With the new language specifications, a top-most class can have both static and non-static classes as its members. With this in mind, we'll define two types of member classes: inner classes and top-level classes.

Top-Level Classes
According to the inner classes specifications[2], two types of classes can be called as top-level classes.
1. A top-most class; i.e., a class that is not enclosed by any other class
2. A static member of another top-level class

Alternatively, a top-level class can be defined as one that cannot directly access instance variables of other classes. In Listing 3, the OuterMost class is a top-level class, as are the StaticNestedOne and StaticNestedTwo classes. As we can see from this example, the static top-level classes can also be nested.

Inner Classes
According to the inner classes specifications[2], the following three types of classes are qualified to be called as inner classes.
1. A class that is declared as a non-static member of another class. We'll define such classes as member inner classes1. It is declared within the class body, but outside a block. In Listing 2, the CommandPanel class and the DisplayCommand class are the member inner classes of ImageViewer. In Listing 3, InnerOne and InnerTwo are the member inner classes of the OuterMost class.
2. A class declared within a block. Such classes are defined as local classes.
3. A class embedded in an expression. In such cases, inner classes do not require a name or constructor. Such classes are defined as anonymous classes.

An inner class itself can have non-static classes nested declared within its body. In Listing 3, InnerNestedOne is nested within InnerOne.

Interfaces also can be declared as inner classes. Unlike inner classes, inner interfaces can have a static final variable declared in them. In Listing 3, the IDPrinter interface is declared within the InnerOne class and it has a static final variable.

Member Inner Classes
In this section, we'll discuss different aspects of member inner classes.

As per the inner classes specifications, an inner class can not have the same name as its enclosing classes. Furthermore, its name can not be the same as the name of the package to which it belongs.

Just like the other members of a class, a member inner class can be declared with the following access modifiers: private, protected and public. If the no access modifier is associated with a class, the visibility is package. Inner classes can also be abstract or final. As per the definition of inner classes, neither the inner class nor it's members can be declared static.

Accessing Inner Class Members
Members of an inner class include non-static variables, methods and classes. Except for members with private scope, inner class members can be accessed/used by enclosing classes. With appropriate access modifiers, they can also be accessed/used by other classes within or outside the package.

In order to access or use an inner-class member, an enclosing class related qualifier is always required. When the inner-class member is a class, it is referred to as .. When it is a variable or method, it can be referenced from the enclosing scope as well as from outside using the notation .. See the Outside class in Listing 3 for examples.

Accessing Enclosing Class Members
Members of the enclosing classes can be accessed/used from its inner classes with or without explicit qualifiers.

Implicit Access
An inner class can directly access an enclosing class variable irrespective of its access modifier. Similarly, an inner class can use a class member of the enclosing class to create objects or for subclassing purposes. Just like variables, an inner class can use the class members in the enclosing scope irrespective of their access modifiers. In Listing 3, the printAllClasses method in the InnerNestedOne class uses a private class called InnerTwo in the enclosing scope to create an object and print its name.

Unlike variables and classes, inner classes cannot use the private methods in the enclosing scope. Trying to access private methods will result in compile-time error. But methods with protected, package and public scope can be used inside an inner class without any explicit qualifiers.

Explicit Reference
If an inner class or its super classes have a member which bears the same name/signature as the one in the enclosing scope, the enclosing name is hidden. In such cases, the enclosing member can be accessed using explicit qualifiers.

Within the inner class, its enclosing instance is referred to as .this. This notation is used for referring to its enclosing class variables and methods. In the ImageViewer example, the displayImage method can be accessed explicitly from the DisplayCommand class by: ImageViewer.this.displayImage(). Further clarifying the usage of this keyword, within the inner class it refers to the instance of the inner class itself. In the enclosing class, this refers to the enclosing class instance only.

A class member in the enclosing scope can be explicitly referred to as .. In Listing 3, the InnerTwo class can be referred to as OuterMost.InnerTwo.

There is a difference between implicit and explicit access as far as the variables are concerned. While the implicit reference allows access to variables with any type of modifiers, the explicit reference does not allow access to private variables. An explicit reference to a private variable is detected at the compile time itself.

A member inner class can extend a class and/or implement interfaces. The base classes or interfaces can reside within or outside the enclosing scope. Just like a top-level class, an inner class will inherit members (that includes member classes) from its super class. If an inner class has its own nested inner classes, those inner classes also inherit the super class members.

If a member with the same name and signature is available in its outer scope as well as in the super class, without the explicit reference, the super class member takes precedence over the outer scope. As mentioned before, an explicit reference is required whenever such a member in the enclosing scope needs to be used.

Constructing Inner Class Objects
Inner class can be constructed within as well as outside the enclosing scope. Within that scope, an inner object is created just like any other class in the package. However, outside the enclosing scope an instance of the enclosing class is required to instantiate an object from an inner class. This will involve two steps:
1. Creating enclosing class instances
2. Creating an inner class instance

The syntax is as follows: .new . If there are many layers of nesting, all the instances of the enclosing classes have to be in existence. In the example shown in Listing 3, the OuterMost and InnerOne instances are created before the InnerNestedOne object is created.

Extending Inner Classes
There are three different cases involved in extending an inner class:
1. Extending within the enclosing scope: Within the scope of an enclosing class, it is just like another class in the same package.
2. Extending outside the enclosing scope: Since an inner object can not exist without an instance of the enclosing class, the constructor for the inner class should have the enclosing class as one of the arguments. In addition, the first statement in the constructor should invoke the super class constructor with the following syntax: . super(). If the inner class that is extended has several layers of nesting, the enclosing instance immediately above the inner class is passed.

The InnerOneExtended class in Listing 4 extends the InnerNestedOne class. As you can see from the example, the constructor has its immediate instance as one of the arguments. It invokes the super class constructor by using the super keyword. You can also see that all of the enclosing instances need to be created in order to create an instance of the InnerOneExtended class.

3. Extending in inherited classes: A non-static top-level class can inherit inner classes. In the example shown in Listing 5, the OuterMost class is subclassed. Its subclasses automatically inherit non-private members including the inner classes. The InnerNestedOne class is subclassed and the printAllClasses method is overriden.

Local Classes
There are two types of local classes: Named and anonymous classes.

Named Local Classes
A named class is declared within a block, has a name and can have a constructor. Since local classes are not available outside the block, they can not be associated with any access modifiers. Associating an access modifier will result in a compile-time error. However, just like member inner classes, named local classes can be abstract or final, but can't be static.

Anonymous Classes
An anonymous class is an inner class that has no name or constructor. Why would you need such a class? With anonymous classes, it is possible to embed a chunk of code within an expression. A typical use would be to pass the anonymous class as an argument to a method.

No modifiers can be associated with an anonymous class. The syntax for the anonymous class starts with the keyword new. It is followed by the type, which can be either a class or an interface. Anonymous classes don't use the extends or implements keywords.

When an anonymous class is of the class type, it extends that class. The anonymous class can override the methods in the class it extends. In the example in Listing 6, the anonymous class is of WindowAdapter type, which is class in java.awt.event. It has several methods. The anonymous class in this example overrides the windowClosed method.

When an anonymous class is of the interface type, it has to implement that interface. In the dispBtn example in Listing7, the anonymous class is of ActionListener type. It implements the ActionPerformed method which is specified in the ActionListener interface. The ActionPerformed method is invoked only when dispBtn is pressed.

Anonymous classes are typically meant for a small chunk of code. Since they are not reusable, it is preferable to use a named class when the code size is large. Anonymous classes are extremely useful in event handling. Using anonymous classes, adapters can be declared exactly in the place they are used.

Whether it is a named or an anonymous class, the members of the enclosing class can be used with the same rules that are applicable to member inner classes. However, the local classes cannot access the non-final local variables in the enclosing code block because of potential synchronization problems. A local class object can exist even after the enclosing block has finished executing. In the examples in Listings 7 and 8, the anonymous class methods are invoked only when the corresponding event occurs. By that time, the createGUI methods would have finished executing.

An Application Using Inner Classes
The application shown in Figure 1 was originally developed using JDK 1.0. This was modified to use the new delegation event model and inner classes. In addition, a few more classes were added to include menus on the application frame.

There are two main GUI-related classes: CommandPanel and FrameMenubar. The CommandPanel class is the main GUI class which has three inner classes: ImageSelectPanel, CinePanel and StatsPanel. Each of these classes create a panel with AWT components. In these panels, anonymous classes are used to handle events originating from these components.

The FrameMenubar class creates a menu bar which contains three menus: File, Locale and Help. Each of the menus have several menu items. The Help menu has two menu items: Help and About. When clicked, these two menu items spawn dialog boxes. Listing 8 shows the adapter class for the About menu item. This class itself is an inner class of FrameMenubar which creates the about MenuItem component. Here, the AboutAdapter object is constructed and passed as an argument to the about MenuItem's addActionListener method.

The AboutAdapter class implements the actionPerformed method. In this method, a dialog box is constructed using the OkBox class, which is a subclass of the AWT Dialog component. Some variables in the enclosing class are passed as arguments to the OkBox constructor. This dialog box has an OK button. In order to register for the OK button action events, an anonymous class is passed as an argument to the addActionListener method. Note that this class also has the actionPerformed method. When the About menu item is clicked, the ActionPerformed method in the AboutAdapter is invoked. This would spawn a dialog box. When the OK button in the dialog box is clicked, the ActionPerformed method in the anonymous class is invoked. Upon execution of this code, the dialog box is closed. This example shows how adapters can be created within adapters using inner classes.

Although you can write Java programs without using inner classes, such programs would be bulky, less readable and often impractical (especially with the new event model). You can expect future applications/applets to make use of inner classes extensively. Java programs in such applications will look a lot different from programs written using the previous Java releases. While inner classes can be used anywhere, their use will be prominent in GUI-related programming and event handlers.

Using inner classes is not always easy. The syntax is often complicated and scope and visibility rules are not very intuitive. Once you cross these hurdles, it is hard to stop you from using this elegant feature.

1. Gosling J, Joy B and Steele G, "Javaª Language Specification", Addison-Wesley, 1996.
2. "Inner Classes in Javaª 1.1", Draft, Sun Microsystems, Nov., 1996.

More Stories By Lawrence Rodrigues

Lawrence Rodrigues is a senior consultant with Compuware Corp., Milwaukee. He has been developing Java applets and applications, is a contributor to the book "Professional Java: Fundamentals," by Wrox Press, and is also a judge at JARS. Besides Java, his current interests include Image Visualization and Analysis, Computational Geometry and Image Data Compression.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

IoT & Smart Cities Stories
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments t...
If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...