Java Anonymous inner class

Source: Internet
Author: User

reprinted from:Http://blog.sina.com.cn/s/blog_62ea4cf40100mubj.html

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 at the time of creation. This will take another form of the new statement, as follows: New < class or interface > < class body > This form of new statement declares a newly anonymous class that 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 operands of the new statement, followed by the body of the anonymous class. If an anonymous class extends another class, its principals can access the members of the class, the methods that overwrite 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

  1. Interface PR
  2. {
  3. void   print1 ();
  4. }
  5. Public class nonameclass
  6. {
  7. Public PR dest ()
  8. {
  9. return New PR () {
  10. Public void print1 ()
  11. {
  12. System.out.println ("Hello world!!");
  13. }
  14. };
  15. }
  16. Public static void main (String args[])
  17. {
  18. Nonameclass c=New nonameclass ();
  19. PR Hw=c.dest ();
  20. Hw.print1 ();
  21. }
  22. }

A PR can also be a class, but the method you call externally must declare in your class or interface that external methods cannot be called inside an anonymous class

Perhaps the most common use of anonymous classes in Java is to add Listner to the frame.
As follows:

Java code
  1. Import   java.awt.*;
  2. Import   java.awt.event.*;
  3. Public class qframe extends Frame {
  4. Public Qframe () {
  5. this. Settitle (\"My application\");
  6. Addwindowlistener (new windowadapter () {
  7. Public void windowclosing (windowevent e) {
  8. Dispose ();
  9. System.exit (0);
  10. }
  11. });
  12. This   . SetBounds (10,10,200,200);
  13. }
  14. }

An internal anonymous class is an internal class that is built without naming you, that is, a variable that has no reference to the instance.
New Windowadapter () {
public void windowclosing (WindowEvent e) {
Dispose ();
System.exit (0);
}
}
New is to create a Windowadapter object, and the following {} indicates that the action in this parenthesis acts on this default pair of names, and the upper Java program is followed by a function body.
The purpose of this usage is to create an instance of an object and override one of its functions. Open the Windowadapter code to discover. It is an abstract class. It is an implementation of the WindowListener interface. Frame.addwindowlistner (); The argument is a windowlistner, and the implementation is an anonymous class derived from Windowadapter.

1. How to determine the existence of an anonymous class? I don't see a name, it's just a parent new object, no anonymous class name.

First look at the segment pseudo-code
Abstract class Father () {
....
}
public class test{
Father f1 = new Father () {...} Here's an anonymous inner class.
}
In general, the new object will be followed by a semicolon after the parentheses, which is the end of the new object.
However, the presence of anonymous inner classes is different, and the parentheses are followed by curly braces, which are the specific implementations of the new object.
Because we know that an abstract class cannot be directly new, it must have an implementation class before we can new its implementation class.
The pseudo-code above is a father implementation class that represents new, an implementation class that is an anonymous inner class.
In fact, splitting the above anonymous inner class can be


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

2. Considerations for Anonymous internal classes

Note that the declaration of an anonymous class occurs 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 an instance of several different anonymous classes.

Here are a few principles to keep in mind when using anonymous inner classes:
• Anonymous inner classes cannot have a constructor method.
• 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, implementing an interface with its implication or implementing a class.
• Because the anonymous inner class is a local inner class, all restrictions on the local inner class are applied to it.

  · Static Inner 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 inner classes and anonymous classes. When this is used in an anonymous class, this refers to the anonymous class or the inner class itself. 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

The inner classes of the

    java and the nested classes in C + + are fundamentally different: C + + 's nested classes do not have a handle to the wrapper class. Just to express a concept of encapsulation; But Java's inner classes are different, It can access the members of the wrapper class (which means it has a handle to the wrapper class).
      Anonymous inner classes are a simplified notation for inner classes: return new Wrapper {
                         &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP, .....
                                       };
      equivalent to: Wrapped extends Wrapper {
        &NBSP;&NBSP;&NBSP, .....
          }
          return New Wrapped ();

is the anonymous inner class The only thing that works?
Consider a case like this:

Interface ICount {
int count ();
}

Class Parent {
int i = 0;
int count () {
return i++;
}
}
What happens when you have a class child that wants to inherit the count () method of the parent and implement the Count method in the Icount interface? The inner class is ready to go:
Class Child extends Parent {
ICount GetCount () {
return new ICount {
int i = 0;
int count () {
Return (I *= 2);
}
}
}
}

Java anonymous inner class

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.