Tips for using: Internal classes and anonymous classes to optimize Java code

Source: Internet
Author: User
Tags anonymous final implement instance method interface reference requires access
Skills | optimization

Java 1.1 simplifies the implementation of some practical structures by modifying the Java language Specification. Among those modifications, the most striking is the internal class and the anonymous class. If used properly, they can make the program easier to understand and maintain. Let's look at how these features work, how to use them correctly, and how to avoid some common mistakes.

Inner class

Simply put, an "inner class" is a class declared inside another class. Starting with Java 1.1, you can declare another class in one class, which is very similar to declaring fields and methods. A class that wraps an inner class declaration is called an "external class."

In fact, the Java language Specification also allows you to do more things, including:

Declare a class in another class or a port.

Declare an interface in another interface or in a class.

Declare a class in a method.

Class and interface declarations can be nested to any depth.

Listing A is a blank declaration of classes and interfaces that demonstrates these possibilities.

Using an import statement, you can omit package names as you would any other standard class. In addition, in an external class, you can use a simple name to refer to all inner classes and interfaces (see the new statement in listing a). Note It is still necessary to specify Interface1 from the reference Inner2 in Method1 because Inner2 is at a different level.

Table A summarizes the fully qualified names of each of the internal classes and interfaces declared in listing a. After you use the import statement, you can take a shorter form. Of course, in the outer class, you can also omit the name of the outer class.

Name

Class/interface

Inner1 MyPackage. Inner1

Interface1 MyPackage. Interface1

Inner2 MyPackage. Interface1.inner2

Interface2 MyPackage. Interface1.interface2

Inner3 Inner3 is local to Method1, so it cannot be accessed outside of the method

Referencing internal classes

One of the most natural uses of an inner class is to declare a class that is used only within another class, or to declare a class that is closely related to another class. As shown in Listing B, it is a simple implementation of a linked list. Because the node class is typically used only within the scope of the LinkedList, it is a good idea to declare node as an internal class of LinkedList.

Access control modifiers that apply to class members also apply to inner classes, that is, inner classes can have package, protected, private, and public access, and their semantics are no different from normal semantics. Because node is to be used outside of LinkedList, it is declared public.

However, the modifier static has different meanings. When applied to an inner class, the class it declares has the same semantics as the other classes, i.e. it can be instantiated and used like a standard class. The only difference is that it has full access to all static members of the external class. Listing c shows a simple program that creates a linked list and prints it to a standard output device.

Non-static inner class

If the inner class does not specify a static modifier, it has full access to all members of the external classes, including instance fields and methods. To implement this behavior, non-static inner classes store an implicit reference to an instance of an external class.

Therefore, instantiating a non-static inner class requires a new statement with a different syntax:

. New

This form of the new statement requires an instance of the outer class so that the inner class can be created in the context of that instance. Note that listing a declares several non-static inner classes and instantiates them in Method1 with the standard new statement.

You can do that because METHOD1 is an instance method of an external class, so the new statement is implicitly executed in the context of an instance of an external class. You need to use the modified syntax only if you instantiate a non-static inner class outside of the outer class or in the context of another object.

However, non-static inner classes have some limitations. In particular, they cannot declare static initialization lists and static members unless they are in a constant field. In addition, internal classes declared within a method cannot access local variables and parameters of the method unless they are initialized to final.

Anonymous class

Anonymous classes are classes that cannot have names, so there is no way to reference them. They must be declared as part of the new statement when they are created.

This will take another form of the new statement, as follows:

New < class or interface > < class's main >

This form of the new statement declares an anonymous class that expands on a given class, or implements a given interface. It also creates a new instance of that class and returns it as the result of the statement. The class to extend and the interface to implement are the operands of the new statement, followed by the body of the anonymous class.

If an anonymous class expands on another class, its principal can access the members of the class, the methods that override it, and so on, which is the same as any other standard class. If an anonymous class implements an interface, its principal must implement the method of the interface.

Note that the declaration of an anonymous class is done at compile time, and the instantiation occurs at run time. This means that a new statement in the For loop creates several instances of the same anonymous class, rather than creating one instance of several different anonymous classes.

Technically, anonymous classes can be considered non-static internal classes, so they have the same permissions and restrictions as the non-static inner classes declared within the method.

An anonymous class is useful if the task you want to perform requires an object, but it is not worth creating an entirely new object (either because the required class is too simple or because it is used only within one method). Anonymous classes are especially good for creating event handlers quickly in swing applications.

Listing d is a very simple swing application that shows several concepts related to anonymous classes. This example creates two anonymous classes. The first extends the Java.awt.event.WindowAdapter and invokes the application's OnClose method when the application window closes.

Even if OnClose is declared private, anonymous classes can call it, because an anonymous class is essentially an internal class of application classes. The second anonymous class implements the Java.awt.ActionListener interface, which closes the application window after a button is pressed. Note the anonymous class can access the local variable frame. This is because anonymous classes are declared inside the same method as the frame. However, a build error will be generated if the frame is declared final.

More-Optimized code

The internal and anonymous classes are the two great tools that Java 1.1 offers us. They provide better encapsulation, and the result is that the code is easier to understand and maintain, so that the related classes can exist in the same source code file (thanks to the inner class) and avoid a program producing a large number of very small classes (thanks to anonymous classes).



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.