An anonymous inner class is suitable for creating a class that needs to be used only once, such as command objects that are required in order mode. The syntax of the anonymous inner class is a little odd, and creating an anonymous inner class immediately creates an instance of the class, which disappears immediately and the anonymous inner class cannot be reused.
The format for defining anonymous inner classes is as follows:
New parent class Constructor (parameter list) | Implement Interface ()
{
//anonymous inner class part
}
As you can see from the above definition, an anonymous inner class must inherit a parent class, or implement an interface, but can inherit at most one parent class, or implement an interface.
There are two rules for anonymous inner classes as follows:
1 anonymous inner class cannot be an abstract class, because the system creates an object of an inner class immediately when it creates an anonymous inner class. Therefore, anonymous inner classes are not allowed to be defined as abstract classes.
2 the anonymous inner class inequality definition constructor, because the anonymous inner class does not have a class name, so the constructor cannot be defined, but the anonymous inner class can define the instance initialization block to accomplish what the constructor needs to do through the instance initialization block.
Interface Product { public double getprice ();
public String getName (); public class Testanonymous { public void Test (Product p) { &nbs P
System.out.println ("bought a" + p.getname () + ", flowers Out" + p.getprice ()); } public static void Main (string[] args) { & nbsp
Testanonymous ta = new testanonymous (); ta.test (New Product () { public Double GetPrice () {
return 567; } public String GetName () { return
"AGP video card"; }
});
}}
As long as a class is abstract or an interface, the methods in its subclasses can be implemented using anonymous inner classes. The most common scenario is on multithreaded implementations, because the thread class must inherit or inherit the Runnable interface to implement multithreading.
Anonymous inner class implementation of the thread class:
public class Demo {public
static void Main (string[] args) {
thread t = new Thread () {public
void run () {
for (int i = 1; I <= 5; i++) {
System.out.print (i + "");}}}
;
T.start ();
}
Anonymous inner class implementation of the Runnable interface:
public class Demo {public
static void Main (string[] args) {
Runnable r = new Runnable () {public
void run ( {for
(int i = 1; I <= 5; i++) {
System.out.print (i + "");}}}
;
Thread t = new Thread (r);
T.start ();
}