Anonymous class)

Source: Internet
Author: User

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.

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.