Java anonymous internal class instance analysis

Source: Internet
Author: User

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 form of new statement, as shown below: new <class or interface> <class subject> in this form of new statement declares a new anonymous class, it 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.
Java code Copy codeThe Code is as follows: interface pr
{
Void print1 ();
}
Public class noNameClass
{
Public pr dest ()
{
Return new pr (){
Public void print1 ()
{
System. out. println ("Hello world !! ");
}
};
}
Public static void main (String args [])
{
NoNameClass c = new noNameClass ();
Pr hw = c. dest ();
Hw. print1 ();
}
}

Pr can also be a class, but the method you call externally must declare in your class or interface that the external cannot call the internal method of the anonymous class
The most frequently used internal anonymous classes in Java may be the addition of Listner in the Frame.
As follows:
Java codeCopy codeThe Code is as follows: import java. awt .*;
Import java. awt. event .*;
Public class QFrame extends Frame {
Public QFrame (){
This. setTitle (\ "my application \");
AddWindowListener (new WindowAdapter (){
Public void windowClosing (WindowEvent e ){
Dispose ();
System. exit (0 );
}
});
This. setBounds (10, 10, 200,200 );
}
}

An internal Anonymous class is an internal class, but it is not named for you, that is, the instance variable is not referenced.Copy codeThe Code is as follows: new WindowAdapter (){
Public void windowClosing (WindowEvent e ){
Dispose ();
System. exit (0 );
}
}

New is to create a WindowAdapter object, and the next {} indicates that the operation in this bracket acts on this default pair name, and the above Java program is followed by a function body.
This usage is used to create an instance of an object and override its function. Open the WindowAdapter code. It is an abstract class. It is an implementation of the WindowListener interface. Frame. addWindowListner (); is a WindowListner parameter, which is implemented by passing an anonymous class derived from WindowAdapter.
1. How can I determine the existence of an anonymous class? The name is invisible. It seems that the parent class has a new object and there is no Anonymous class name.
First look at the pseudo code segmentCopy codeThe Code is as follows: abstract class Father (){
....
}
Public class Test {
Father f1 = new Father () {...} // here is an anonymous internal class
}

In general, the new object should be a semicolon after the parentheses, that is, the new output object will end the statement.
However, when an anonymous internal class is displayed, the parentheses are followed by braces, and the braces are specific implementation methods of the new output object.
Because we know that an abstract class cannot be new directly, we must first have an implementation class before we can get a new implementation class.
The pseudo code above indicates that the new is the Father implementation class, which is an anonymous internal class.
In fact, the above anonymous internal class can be splitCopy codeThe Code is as follows: class SonOne extends Father {
... // The code here is the same as the code in the braces of the anonymous internal class above.
}
Public class Test {
Father f1 = new SonOne ();
}

2. Considerations for anonymous internal classes
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.
When using anonymous internal classes, remember the following principles:
· No constructor is allowed for anonymous internal classes.
· Anonymous internal classes cannot define any static members, methods, and classes.
· Anonymous internal classes cannot be public, protected, private, or static.
· Only one instance of the anonymous internal class can be created.
· An anonymous internal class must be behind new and be used to implicitly implement an interface or implement a class.
· Because the anonymous internal class is a local internal class, all restrictions on the local internal class take effect.
· Internal classes can only access static variables or static methods of external classes.
This in the anonymous class and internal class:
Sometimes, some internal and anonymous classes are used. When this is used in an anonymous class, this refers to the anonymous class or internal class itself. If we want to use external class methods and variables, we should add the Class Name of the external class.
3. Functions of anonymous internal classes
The internal class of Java is essentially different from the nested class in C ++: The nested class of C ++ does not point to the handle of the packaging class. It only expresses the concept of an encapsulation. But Java internal classes are different, and it can access the members of the packaging class (this indicates that it has a handle pointing to the packaging class ).
The anonymous internal class is a simplified way of writing internal classes: return new Wrapper {
...
};
Equivalent to: Wrapped extends Wrapper {
...
}
Return new Wrapped ();
Does the anonymous internal class only play this role?
Consider this case:Copy codeThe Code is as follows: interface ICount {
Int count ();
}
Class Parent {
Int I = 0;
Int count (){
Return I ++;
}
}

There is a Child class that inherits the count () method of Parent and implements the count method in the ICount interface. What should I do at this time? Internal classes can show their talents:Copy codeThe Code is as follows: class Child extends Parent {
ICount getCount (){
Return new ICount {
Int I = 0;
Int count (){
Return (I * = 2 );
}
}
}
}

Read this codeCopy codeThe Code is as follows: public static void main (String [] args ){
TheApp = new Analyzer ();
SwingUtilities. invokeLater (new Runnable () {// Anonymous Runnable class
// Object
Public void run () {// Run method executed in thread
TheApp. creatGUI (); // Call static GUI creator
}
});
}
Public static void main (String [] args ){
TheApp = new Analyzer (); // create an object
SwingUtilities. invokeLater (new Runnable () {// Anonymous Runnable class
// An anonymous internal class that implements a thread
// The original method is to pass a Runnable type parameter // here we can use this anonymous class method to implement
// Object
Public void run () {// Run method executed in thread
TheApp. creatGUI (); // Call static GUI creator
}
});
}

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.