|By Lawrence Rodrigues||
|April 1, 1997 12:00 AM EST||
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.
According to the inner classes specifications, 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.
According to the inner classes specifications, 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
Accessing Enclosing Class Members
Members of the enclosing classes can be accessed/used from its inner classes with or without explicit qualifiers.
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.
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
A class member in the enclosing scope can be explicitly referred to as
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:
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:
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.
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.
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.
I wanted to gather all of my Internet of Things (IOT) blogs into a single blog (that I could later use with my University of San Francisco (USF) Big Data “MBA” course). However as I started to pull these blogs together, I realized that my IOT discussion lacked a vision; it lacked an end point towards which an organization could drive their IOT envisioning, proof of value, app dev, data engineering and data science efforts. And I think that the IOT end point is really quite simple…
Jul. 28, 2016 07:15 PM EDT Reads: 1,225
"My role is working with customers, helping them go through this digital transformation. I spend a lot of time talking to banks, big industries, manufacturers working through how they are integrating and transforming their IT platforms and moving them forward," explained William Morrish, General Manager Product Sales at Interoute, in this SYS-CON.tv interview at 18th Cloud Expo, held June 7-9, 2016, at the Javits Center in New York City, NY.
Jul. 28, 2016 05:30 PM EDT Reads: 2,212
You think you know what’s in your data. But do you? Most organizations are now aware of the business intelligence represented by their data. Data science stands to take this to a level you never thought of – literally. The techniques of data science, when used with the capabilities of Big Data technologies, can make connections you had not yet imagined, helping you discover new insights and ask new questions of your data. In his session at @ThingsExpo, Sarbjit Sarkaria, data science team lead ...
Jul. 28, 2016 04:30 PM EDT Reads: 1,183
Extracting business value from Internet of Things (IoT) data doesn’t happen overnight. There are several requirements that must be satisfied, including IoT device enablement, data analysis, real-time detection of complex events and automated orchestration of actions. Unfortunately, too many companies fall short in achieving their business goals by implementing incomplete solutions or not focusing on tangible use cases. In his general session at @ThingsExpo, Dave McCarthy, Director of Products...
Jul. 28, 2016 04:15 PM EDT Reads: 1,773
WebRTC is bringing significant change to the communications landscape that will bridge the worlds of web and telephony, making the Internet the new standard for communications. Cloud9 took the road less traveled and used WebRTC to create a downloadable enterprise-grade communications platform that is changing the communication dynamic in the financial sector. In his session at @ThingsExpo, Leo Papadopoulos, CTO of Cloud9, discussed the importance of WebRTC and how it enables companies to focus...
Jul. 28, 2016 03:45 PM EDT Reads: 1,027
Verizon Communications Inc. (NYSE, Nasdaq: VZ) and Yahoo! Inc. (Nasdaq: YHOO) have entered into a definitive agreement under which Verizon will acquire Yahoo's operating business for approximately $4.83 billion in cash, subject to customary closing adjustments. Yahoo informs, connects and entertains a global audience of more than 1 billion monthly active users** -- including 600 million monthly active mobile users*** through its search, communications and digital content products. Yahoo also co...
Jul. 28, 2016 03:15 PM EDT Reads: 706
A critical component of any IoT project is what to do with all the data being generated. This data needs to be captured, processed, structured, and stored in a way to facilitate different kinds of queries. Traditional data warehouse and analytical systems are mature technologies that can be used to handle certain kinds of queries, but they are not always well suited to many problems, particularly when there is a need for real-time insights.
Jul. 28, 2016 03:15 PM EDT Reads: 1,906
Amazon has gradually rolled out parts of its IoT offerings in the last year, but these are just the tip of the iceberg. In addition to optimizing their back-end AWS offerings, Amazon is laying the ground work to be a major force in IoT – especially in the connected home and office. Amazon is extending its reach by building on its dominant Cloud IoT platform, its Dash Button strategy, recently announced Replenishment Services, the Echo/Alexa voice recognition control platform, the 6-7 strategic...
Jul. 28, 2016 12:30 PM EDT Reads: 613
The best-practices for building IoT applications with Go Code that attendees can use to build their own IoT applications. In his session at @ThingsExpo, Indraneel Mitra, Senior Solutions Architect & Technology Evangelist at Cognizant, provided valuable information and resources for both novice and experienced developers on how to get started with IoT and Golang in a day. He also provided information on how to use Intel Arduino Kit, Go Robotics API and AWS IoT stack to build an application tha...
Jul. 28, 2016 12:00 PM EDT Reads: 1,241
IoT generates lots of temporal data. But how do you unlock its value? You need to discover patterns that are repeatable in vast quantities of data, understand their meaning, and implement scalable monitoring across multiple data streams in order to monetize the discoveries and insights. Motif discovery and deep learning platforms are emerging to visualize sensor data, to search for patterns and to build application that can monitor real time streams efficiently. In his session at @ThingsExpo, ...
Jul. 28, 2016 11:15 AM EDT Reads: 1,154
SYS-CON Events announced today that LeaseWeb USA, a cloud Infrastructure-as-a-Service (IaaS) provider, will exhibit at the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. LeaseWeb is one of the world's largest hosting brands. The company helps customers define, develop and deploy IT infrastructure tailored to their exact business needs, by combining various kinds cloud solutions.
Jul. 28, 2016 10:45 AM EDT Reads: 1,292
SYS-CON Events announced today that 910Telecom will exhibit at the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Housed in the classic Denver Gas & Electric Building, 910 15th St., 910Telecom is a carrier-neutral telecom hotel located in the heart of Denver. Adjacent to CenturyLink, AT&T, and Denver Main, 910Telecom offers connectivity to all major carriers, Internet service providers, Internet backbones and ...
Jul. 28, 2016 10:30 AM EDT Reads: 839
Big Data, cloud, analytics, contextual information, wearable tech, sensors, mobility, and WebRTC: together, these advances have created a perfect storm of technologies that are disrupting and transforming classic communications models and ecosystems. In his session at @ThingsExpo, Erik Perotti, Senior Manager of New Ventures on Plantronics’ Innovation team, provided an overview of this technological shift, including associated business and consumer communications impacts, and opportunities it ...
Jul. 28, 2016 10:00 AM EDT Reads: 287
SYS-CON Events announced today that Venafi, the Immune System for the Internet™ and the leading provider of Next Generation Trust Protection, will exhibit at @DevOpsSummit at 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Venafi is the Immune System for the Internet™ that protects the foundation of all cybersecurity – cryptographic keys and digital certificates – so they can’t be misused by bad guys in attacks...
Jul. 28, 2016 09:30 AM EDT Reads: 1,419
It’s 2016: buildings are smart, connected and the IoT is fundamentally altering how control and operating systems work and speak to each other. Platforms across the enterprise are networked via inexpensive sensors to collect massive amounts of data for analytics, information management, and insights that can be used to continuously improve operations. In his session at @ThingsExpo, Brian Chemel, Co-Founder and CTO of Digital Lumens, will explore: The benefits sensor-networked systems bring to ...
Jul. 28, 2016 09:00 AM EDT Reads: 1,622
Manufacturers are embracing the Industrial Internet the same way consumers are leveraging Fitbits – to improve overall health and wellness. Both can provide consistent measurement, visibility, and suggest performance improvements customized to help reach goals. Fitbit users can view real-time data and make adjustments to increase their activity. In his session at @ThingsExpo, Mark Bernardo Professional Services Leader, Americas, at GE Digital, discussed how leveraging the Industrial Internet a...
Jul. 28, 2016 07:30 AM EDT Reads: 548
There will be new vendors providing applications, middleware, and connected devices to support the thriving IoT ecosystem. This essentially means that electronic device manufacturers will also be in the software business. Many will be new to building embedded software or robust software. This creates an increased importance on software quality, particularly within the Industrial Internet of Things where business-critical applications are becoming dependent on products controlled by software. Qua...
Jul. 28, 2016 06:45 AM EDT Reads: 1,589
In addition to all the benefits, IoT is also bringing new kind of customer experience challenges - cars that unlock themselves, thermostats turning houses into saunas and baby video monitors broadcasting over the internet. This list can only increase because while IoT services should be intuitive and simple to use, the delivery ecosystem is a myriad of potential problems as IoT explodes complexity. So finding a performance issue is like finding the proverbial needle in the haystack.
Jul. 28, 2016 05:45 AM EDT Reads: 2,340
The 19th International Cloud Expo has announced that its Call for Papers is open. Cloud Expo, to be held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, brings together Cloud Computing, Big Data, Internet of Things, DevOps, Digital Transformation, Microservices and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding business opportuni...
Jul. 28, 2016 03:15 AM EDT Reads: 2,663
Large scale deployments present unique planning challenges, system commissioning hurdles between IT and OT and demand careful system hand-off orchestration. In his session at @ThingsExpo, Jeff Smith, Senior Director and a founding member of Incenergy, will discuss some of the key tactics to ensure delivery success based on his experience of the last two years deploying Industrial IoT systems across four continents.
Jul. 28, 2016 03:00 AM EDT Reads: 1,658