java-Anonymous Inner class

Source: Internet
Author: User

Anonymous inner class

1. Definition:

Implement an interface, or inherit a parent class, and return a good instance of new.

2. Syntax:

The implementation body of the new class name or interface name class

3. What is the use of anonymous internal classes:

Class is used immediately after it is created and is used only once

4. Note the point:

• Anonymous inner classes cannot have a constructor • Anonymous inner classes cannot define any static members, static methods. • Anonymous internal classes 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. 5. Lifting chestnuts implement anonymous inner classes by inheriting:
1  PackageCom.han6.java;2 3  Public classFruit4 {5      Public voidsaysomething ()6     {7System.out.println ("I am fruit! ");8     }9     Ten      Public Static voidMain (string[] args) One     { AFruit Fruit =NewFruit () -         { - @Override the              Public voidsaysomething () { -System.out.println ("I am apple!"); -             } -              +         }; - fruit.saysomething (); +     } A  at}

Use anonymous inner classes by implementing an interface:
1  PackageCom.han6.java;2 3  Public classDemo4 {5      Public Static voidMain (string[] args)6     {7Person person =NewPerson ()8         {9 @OverrideTen              Public voidEat () One             { ASystem.out.println ("A person like to eat fruit!"); -             } -         }; the person.eat (); -     } -      - } +  - Interface Person + { A     voideat (); at}

6. Work use:

An anonymous inner class is used on a specific instance of = modifies some property methods of the class to which the instance belongs, and the modified content is only valid for this instance as a one-time class. Mainly used in the handling of a particular event.

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.