Optimize Java code using internal and anonymous classes

Source: Internet
Author: User
Use internal and anonymous classes to optimize Java code-general Linux technology-Linux programming and kernel information. The following is a detailed description. By modifying Java language specifications, Java 1.1 significantly simplifies the implementation of some practical structures. Among those modifications, internal classes and anonymous classes are the most notable. If used properly, they can make the program easier to understand and maintain. Let's take a look at how these features work, how to use them correctly, and how to avoid some common errors.


Internal class


To put it simply, "internal class" is the class declared inside another class. From Java 1.1, you can declare another class in one class, which is very similar to declaring fields and methods. Classes that wrap internal class declarations are called "external classes ".

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

Declare a class in another class or interface.
Declare an interface in another interface or class.
Declare a class in a method.
Class and interface declaration can be nested in any depth.
Listing A is A blank declaration of classes and interfaces, which demonstrates these possibilities.

Using an import Statement, You can omit the package name as if you were using any other standard class. In addition, A simple name can be used to reference all internal classes and interfaces (see the new statement in listing ). Note: To reference Inner2 from Method1, you still need to specify Interface1 because Inner2 is at a different level.

Table A summarizes the fully qualified names of each internal class and interface declared in listing. After the import Statement is used, a short format can be used. You can also omit the name of an external class.

Name
Class/interface

Inner1 mypackage. Inner1
Interface1 mypackage. Interface1
Inner2 mypackage. Interface1.Inner2
Interface2 mypackage. Interface1.Interface2
Inner3 Inner3 is local for Method1, so it cannot be accessed outside the method.

Reference internal class



One of the most natural applications of internal classes is to declare classes that are used only within the other class, or declare classes that are closely related to the other class. As shown in List B, it is a simple implementation of a linked list. Because the Node class is generally used only within the scope of the consumer list, it is best to declare Node as an internal class of the consumer list.

The access control modifier for Class Members also applies to internal classes. That is to say, internal classes can have package, protected, private, and public Access Permissions. Their semantics is no different from normal semantics. Node should be declared as public because it should be used outside the consumer list.

However, the modifier static has different meanings. When applied to an internal class, the declared class has the same semantics as other classes, that is, it can be instantiated and used as a standard class. The only difference is that it has full access permissions to all static members of the External Department class. Listing C shows a simple program that creates a linked list and prints it to a standard output device.

Non-static internal class


If the internal class does not specify a static modifier, it will have full access permissions to all members of the external class, including instance fields and methods. To implement this row, a non-static internal class stores an implicit reference to an external class instance.

Therefore, to instantiate a non-static internal class, you must use a new statement with different syntaxes:


. New

This new statement requires an instance of the external class so that the internal class can be created in the context of that instance. Note that listing A declares several non-static internal classes and instantiates them in Method1 using the standard new statement.

This is because Method1 is an instance method of the external class. Therefore, the new statement is implicitly executed in the context of an instance of the external class. The modified syntax is required only when a non-static internal class is instantiated outside the external class or in the context of other objects.

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


Anonymous class

Anonymous classes cannot be referenced because they cannot have names. They must be declared as part of the new statement at creation.

This requires another new statement, as shown below:


New <类或接口> <类的主体>

This new statement declares a new anonymous class, which extends 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 be extended and the interface to be implemented are the operands of the new statement, followed by the subject of the anonymous class.

If an anonymous class is extended to another class, its subject can be a member of the class, override its method, and so on, which is the same as any other standard class. If an anonymous class implements an interface, its subject must implement the interface method.

Note that the declaration of anonymous classes is implemented at compilation and instantiation is performed at runtime. This means that a new statement in the for Loop will create several instances of the same Anonymous class, rather than creating several instances of different anonymous classes.

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

If the task needs an object, but it is not worth creating a new object (probably because the required class is too simple, or because it is only used within a method ), anonymous classes are very useful. Anonymous classes are especially suitable for quickly creating event handlers in Swing applications.

Listing D is a very simple Swing application that shows several concepts related to anonymous classes. In this example, two anonymous classes are created. First, expand java. awt. event. WindowAdapter and call the onClose method of the application when the application window is closed.


Even if onClose is declared as private, the anonymous class can call it because the Anonymous class is essentially an internal class of the application class. The second Anonymous class implements the java. awt. ActionListener interface, which closes the application window after a button is pressed. Note that anonymous classes can access the local variable frame. This is because the Anonymous class is declared within the same method as the frame. However, the frame should be declared as final; otherwise, a compilation error will be generated.


More Optimized Code

The internal and anonymous classes are two outstanding tools provided by Java 1.1. They provide better encapsulation, and the result is that the Code is easier to understand and maintain, so that the relevant classes can exist in the same source code file (thanks to internal classes ), and avoid a program from generating a large number of very small classes (thanks to anonymous classes ).
Related Article

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.