When the class name of an internal class is used only once when such an object is created, and the new class to be generated must inherit from an existing parent class or implement an interface, in order to consider using an anonymous class, the anonymous class itself is unknown, so it does not have a constructor. It needs to explicitly call the constructor of a parent class without parameters, and override the method of the parent class. The so-called anonymity means that the class does not even have a name, but only explicitly calls the constructor of a parent class without parameters.
Example
Import java. AWT .*;
Import java. AWT. event .*;
Public class anonymousclass {
Private frame F;
Private textfield TF;
Public anonymousclass (){
F = new frame ("inner classes example ");
TF = new textfield (30 );
}
Public void launchframe (){
Label Label = new label ("Click and drag the mouse ");
F. Add (Label, borderlayout. North );
F. Add (TF, borderlayout. South );
F. addmousemotionlistener (New mousemotionadapter () {// Anonymous class starts
Public void mousedragged (mouseevent e ){
String S = "Mouse dragging: x =" + E. getx () + "Y =" + E. Gety ();
TF. settext (s );}
}); // End of the anonymous class
F. setsize (300,200 );
F. setvisible (true );
}
Public static void main (string ARGs []) {
Anonymousclass OBJ = new anonymousclass ();
OBJ. launchframe ();
}
}
In fact, after careful analysis, in this example, the use of anonymous classes and internal classes can achieve the same functions, but the method is different. From the use of internal classes to the use of anonymous classes, it can be said that the relationship between classes is becoming increasingly unclear, but the program is becoming more and more concise. The familiarity with these two methods also helps you to compile a graphic interface program.