A Discussion on JAVA anonymous internal classes, callback, and event Modes

Source: Internet
Author: User

A Discussion about JAVA anonymous internal classes.
Basic Theory:
-----------------------------------------------------
JAVA internal class: the definition of an internal class is defined within another class.

The reason is:

1. An internal class object can access the implementation of the object created for it, including private data. That is, an internal class instance is privileged to the instance of the class that contains it.

2. for other classes in the same package, the internal class can be hidden. In other words, the internal class, regardless of the method visibility, may be public. In addition to the inclusive class, other classes cannot use it.

3. Anonymous internal classes can easily define callbacks.

4. Use internal classes to easily write event drivers.

In fact, it is only intended to define callback-further, it is event-driven.

Interface and callback: a common programming mode is the callback mode. In this mode, you can specify the method of the callback object when a specific time occurs.
--------------------------------------------------
Note:
 
This in the anonymous class and internal class:
Sometimes, some internal and anonymous classes are used. When this is used in an anonymous class, this refers to the anonymous class or internal class itself.
If we want to use external class methods and variables, we should add the Class Name of the external class. For example:

Public class {
Int I = 1;

Public (){
Thread thread = new Thread (){
Public void run (){
For (;;){
A. this. run ();
Try {
Sleep (1000 );
} Catch (InterruptedException ie ){
}
}
}
};
Thread. Start ();
}

Public void run (){
System. Out. println ("I =" + I );
I ++;
}

Public static void main (string [] ARGs) throws exception {
New ();
}

}

 

In the above example, thread is an anonymous class object. In its definition, its run function uses the run function of the external class.
In this case, the function cannot be called directly due to the same name. At this time, there are two ways, one is to change the external run function name, but this method is not available for an application that has been developed to the middle of the process.
. Then we can use the method in this example to add this reference to the Class Name of the external class to indicate that the method run of the external class is called.
--------------------------------------------------


For this example:

This. Test (new inner (){
Public void Method1 (){
System. Out. Print ("1111 ");
}

Public void method2 (){
System. out. print ("22222 ");
}
});

At this time, call the test () method. When will the method1 and method2 of the Inner class be called? Is this object sending messages to them (for example, passing in a parameter? Or is it an explicit call ??
 
For the Inner class, except for this class, it is this. test (... in that sentence, this can call the Inner class method, but not elsewhere. However, this also requires you to save a reference to this internal class instance in the class. Once again, the internal class is used to call the external method at a certain time and exists-this is the callback.

To demonstrate that the internal class instance method can only be called in an inclusive class instance, but cannot be called elsewhere, the following is an example:

JAVA2 practical tutorial source code:

/** An application to demonstrate the use of internal Classes */

/** Class Outer */
Class Outer {
Private static int size;

/** Internal class Inner Declaration */
Public class Inner {
Private int size;

/** Method doStuff ()*/
Public void doStuff (int size ){
Size ++; // access local variables
This. Size ++; // access the member variables of its internal class
Outer. This. Size ++; // access the member variables of its external class
System. Out. println (size + "" + this. Size + "" + outer. This. size );
}
} // Internal class inner ends

/** Instance method testinner () method defined in class Outer */
Public void testinner (){
Inner I = new inner ();
I. dostuff (5 );
}

/** Main () method */
Public static void main (string [] ){
Outer o = new outer ();
O. testinner ();
}
} // Class outer ends

------------------------------------------------
So how can we use internal classes and anonymous classes for event processing?

JAVA --- event Adapter

1. Event adapter -- EventAdapter

In the following example, the mouse adapter is used:
  

Import java. AWT .*;
Import java. AWT. event .*;
Public class mouseclickhandler extends mouseadaper {
Public void mouseclicked (mouseevent e) // only implement the required Method
{......}
}

The event adapter classes defined in the java. awt. event package include the following:
1. ComponentAdapter (Component adapter)
2. ContainerAdapter (container adapter)
3. FocusAdapter (Focus adapter)
4. KeyAdapter (Keyboard adapter)
5. MouseAdapter (mouse adapter)
6. MouseMotionAdapter (mouse movement adapter)
7. WindowAdapter)

2. Implement event processing using internal classes

The internal class is defined in another class. The main reason for using the internal class is as follows:
◇ An internal class object can access the member methods and variables of the external class, including private members.
◇ When implementing event listeners, it is very easy to implement functions using internal and Anonymous class programming.
◇ Compile the event driver, and the internal class is very convenient.
Therefore, the internal class can be applied in the AWT event processing mechanism.

Example 5.11
   

Import java. AWT .*;
Import java. AWT. event .*;
Public class innerclass {
Private frame F;
Private textfield TF;
Public innerclass (){
F = new frame ("inner classes example ");
TF = new textfield (30 );
}

Public voidi launchframe (){
Label Label = new label ("Click and drag the mouse ");
F. Add (Label, borderlayout. North );
F. Add (TF, borderlayout. South );
F. addmousemotionlistener (New mymousemotionlistener ();/* the parameter is an internal class object */
F. setsize (300,200 );
F. setvisible (true );
}

Class mymousemotionlistener extends mousemotionadapter {/* internal class start */
Public void mousedragged (mouseevent e ){
String S = "Mouse dragging: x =" + E. getx () + "Y =" + E. Gety ();
TF. settext (s );}
};

Public static void main (string ARGs []) {
Innerclass OBJ = new innerclass ();
OBJ. launchframe ();
}
} // Internal class ends
}

 

3. Anonymous Class)

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 a parent with no parameters.
Class constructor, and override the parent class method. 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 5.12
   

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, for example, 5.11 and 5.12 implement the same functions, but they adopt different methods. In 5.11, the event processing class is an internal class, while in 5.12, the event processing class is an anonymous class. It can be said that the relationship between classes is increasingly unclear,
Is the program is becoming more and more concise. Familiarity with these two methods can also be very helpful for programming graphical interfaces.

If you practice it in IDE, you will understand it more deeply.

From: http://www.cnblogs.com/sgsoft/archive/2004/09/11/42148.html

Related Article

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.