Anonymous inner classes in Java

Source: Internet
Author: User

First, use anonymous inner class inner class

Anonymous inner class because there is no name, it is created in a somewhat strange way. The creation format is as follows:

New Parent class constructor (argument list) | Implement Interface ()      {       // Anonymous inner class-body part      }

Here we see the use of anonymous inner classes we have to inherit a parent class or implement an interface, and of course only inherit one parent class or implement an interface. It also does not have the class keyword, because the anonymous inner class is a reference that uses new directly to generate an object. Of course, this reference is implicit.

For example:

        New Priorityqueue<integer> (                new comparator<integer>() {                    public  int  Compare (integer i, Integer j) {                        int result = i% 2-j% 2;                         if (Result = =0                            ) = i- j;                         return result;                    }        );

Second, the matters needing attention

In the process of using anonymous inner classes, we need to pay attention to the following points:

1 . When using anonymous inner classes, we must inherit a class or implement an interface, but both cannot be combined, and can inherit only one class or implement an interface.

2 . The constructor cannot be defined in an anonymous inner class.

3 . No static member variables and static methods can exist in the anonymous inner class.

4 . The anonymous inner class is a local inner class, so all the limitations of the local inner class also take effect on the anonymous inner class.

5 . An anonymous inner class cannot be abstract, it must implement all the abstract methods of an inherited class or an implemented interface.

Reference: http://blog.csdn.net/chenssy/article/details/13170015

Anonymous inner classes in Java

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.