Java Anonymous class

Source: Internet
Author: User
Tags java anonymous class
Java Anonymous class (not negligible (New + Interface) is a form of defining anonymous classes)

An anonymous internal class (an anonymous class is used to understand the function callback, which is unrelated to the thread) said: (anonymous 1 is used to simplify the code, instead, it tells GC that this object is used only once and is recycled once)

Java internal class: the definition of an internal class is defined within another class.

The reason is:

1. An internal class object can access the implementation of the object created for it, including private data. That is, an internal class instance is privileged to the instance of the class that contains it.

2. for other classes in the same package, the internal class can be hidden. In other words, the internal class, regardless of the method visibility, may be public. In addition to the inclusive class, other classes cannot use it.

3. Anonymous internal classes can easily define callbacks.

4. Use internal classes to easily write event drivers.

In fact, it is only intended to define callback-further, it is event-driven.

Interface and callback: a common programming mode is the callback mode. In this mode, you can specify the method of the callback object when a specific time occurs.

The syntax rules for anonymous internal classes in Java seem odd, but like an anonymous array, when you only need to create a Class Object and cannot use its name, using Internal classes can make the Code look concise and clear. Its syntax rules are as follows:

New interfacename () {...}; or new superclassname (){......};

Next we will continue with the example above:

Public class goods3 {
Public contents cont (){
Return new contents (){
Private int I = 11;
Public int value (){
Return I;
}
};
}
}

Here, the cont () method uses an anonymous internal class to directly return an object of the class implementing the contents interface, which looks very concise.

In the anonymous adapter for Java event processing, anonymous internal classes are widely used. For example, add the following code when you want to close the window:

Frame. addwindowlistener (New windowadapter (){
Public void windowclosing (windowevent e ){
System. Exit (0 );
}
});

One thing to note is that the anonymous internal class has no name, so it does not have a constructor (but if this anonymous internal class inherits a parent class that only contains a parameter constructor, these parameters must be included during creation and the corresponding content must be called using the super keyword during implementation ). If you want to initialize its member variables, you can use the following methods:

If it is in an anonymous internal class of a method, you can use this method to pass in the desired parameters, but remember that these parameters must be declared as final.
The anonymous internal class is transformed into a local internal class with a name, so that it can have constructors.
Use the initialization code block in this anonymous internal class.
Why Internal classes?
What are the advantages of Java internal classes? Why Internal classes?

First, let's take a simple example. If you want to implement an interface, but a method in this interface has the same name and parameter as a method in the class you have conceived, what should you do? In this case, you can create an internal class to implement this interface. Since all the content of the internal class is accessible to external departments, this can complete all the functions that you can directly implement this interface.

But you may have to question it. Isn't it enough to change the method?

Indeed, it is unconvincing to use this as a reason to design internal classes.

The real reason is that the internal classes and interfaces in Java can be combined to solve a problem that C ++ programmers often complain about in Java-there is not much inheritance. In fact, the multi-inheritance design of c ++ is very complicated, and Java can implement multi-inheritance effectively by adding interfaces to internal classes.

------------------------------------

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 <class or interface> <class subject>
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 ).

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.