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