A brief analysis of Java anonymous internal class instances _java

Source: Internet
Author: User
Tags abstract anonymous wrapper
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 principal > This form of the new statement declares a novel anonymous class that extends the 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.
Java code
Copy Code code 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 outside must be declared outside of your class or interface that cannot invoke the internal method of the anonymous class
Perhaps the most common use of internal anonymous classes in Java is to add Listner to the frame.
As follows:
Java code
Copy Code code 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);
}
}

The internal anonymous class, is to create an internal class, but did not give you a name, that is, no reference to the instance of the variable.
Copy Code code as follows:

New Windowadapter () {
public void windowclosing (WindowEvent e) {
Dispose ();
System.exit (0);
}
}

New is to create a Windowadapter object, and the following {} indicates that the operation in parentheses acts on this default pair of names, and the above Java program is followed by a function body.
The purpose of this usage is to create an instance of an object and override a function of it. The code to open Windowadapter can be found. It is an abstract class. It is an implementation of the WindowListener interface. Frame.addwindowlistner (); The parameter is a windowlistner, and the implementation is to pass an anonymous class derived from the Windowadapter.
1. How to judge the existence of an anonymous class? Can't see the name, feel just the parent class new one object, no anonymous class name.
Look at the pseudocode first.
Copy Code code as follows:

Abstract class Father () {
....
}
public class test{
Father f1 = new Father () {...}//Here's an anonymous inner class.
}

In general, the new object when the parentheses should be after the semicolon, that is, the new object to the end of the statement.
However, the anonymous inner class is different, and the parentheses are followed by the curly braces, which are the concrete implementations of the new object in braces.
Because we know that an abstract class is not directly new, we have to have the implementation class before we can new its implementation class.
The pseudo code above is the father implementation class that represents new, and this implementation class is an anonymous inner class.
Actually split the anonymous inner class above can be
Copy Code code as follows:

Class Sonone extends father{
...//Here the code is the same as the anonymous inner class above, the code in curly braces is the same
}
public class test{
Father f1 = new Sonone ();
}

2. Anonymous internal class considerations
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.
When using anonymous inner classes, keep in mind the following principles:
• Anonymous inner classes cannot have construction methods.
• Anonymous inner classes cannot define any static members, methods, and classes.
• Anonymous inner class cannot be public,protected,private,static.
• Only one instance of an anonymous inner class can be created.
• An anonymous inner class must be behind new, with its implied implementation of an interface or implementation of a class.
• Because the anonymous inner class is a local inner class, all restrictions on the local inner class are in effect.
• Internal classes can only access static variables or static methods of external classes.
This is in the anonymous class and in the inner class:
Sometimes we use some internal classes and anonymous classes. When this is used in an anonymous class, this refers to the anonymous class or the inner class itself. Then if we want to use the methods and variables of the outer class, we should add the class name of the outer class
3. The role of anonymous internal classes
Java's internal classes and nested classes in C + + are intrinsically different: the C + + nested class does not have a handle to the wrapper class. Expresses only the concept of a package, but the inner class of Java is different, it can access the members of the wrapper class (this means that it has a handle to the wrapper class).
Anonymous inner class is a simplified form of inner class: return new Wrapper {
...
};
Equivalent to: Wrapped extends wrapper {
...
}
return new wrapped ();
is the anonymous inner class The only thing that works?
Consider such a case:
Copy Code code as follows:

Interface Icount {
int count ();
}
Class Parent {
int i = 0;
int count () {
return i++;
}
}

There is a class child, which wants to inherit the count () method of the parent, and to implement the Count method in the Icount interface. The inner class will be able to do the following:
Copy Code code as follows:

Class Child extends Parent {
Icount GetCount () {
return new Icount {
int i = 0;
int count () {
Return (I *= 2);
}
}
}
}

Look at this code.
Copy Code code as follows:

public static void Main (string[) args) {
Theapp = new Analyzer ();
Swingutilities.invokelater (New Runnable () {//Anonymous Runnable class
//object
public void Run () {//R Un method executed in thread
Theapp.creatgui ();//Call Static GUI creator
}
});
}
public static void Main (string[] args) {
Theapp = new Analyzer ();//Create an object
Swingutilities.invokel Ater (New Runnable () {//Anonymous Runnable class
//An anonymous inner class, he implements a thread
//Originally this method is to pass a Runnable type parameter///This can be done through this anonymous class Way to implement the
//object
public void Run () {//Run methods executed in thread
Theapp.creatgui (); 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.