What Is an Anonymous Inner Class?
Anonymous classes are classes that cannot have names. They cannot be referenced. They can only be declared with the New statement when they are created. The declaration of the anonymous class is made at compile time, and the instantiation is performed at run time, which means that a new statement in a for loop will create several instances of the same anonymous class instead of creating one instance of several different anonymous classes.
Anonymous class
Right!
- Inherit a class and override its methods
- Implementing an interface can be multiple
- Case:
- public class TestAnonymousClass {
public static void main (String args []) {
TestAnonymousClass testAnonymousClass = new TestAnonymousClass ();
testAnonymousClass.show ();
}
// An anonymous inner class is constructed in this method private void show () {
Out anony = new Out () {// Get anonymous inner class instance void show () {// Override the method of the parent class System.out.println ("this is Anonymous InterClass showing.");
}
};
anony.show (); // call its method}
}
// Existing class Out; anonymous inner class gets another implementation by overriding its method class Out {
void show () {
System.out.println ("this is Out showing.");
} [1]
}
- Anonymous classes are classes that cannot have names. They cannot be referenced. They can only be declared with the New statement when they are created. The declaration of the anonymous class is made at compile time, and the instantiation is performed at run time, which means that a new statement in a for loop will create several instances of the same anonymous class instead of creating one instance of several different anonymous classes.
- The purpose of an anonymous class is to require a special implementation somewhere, so write its implementation there, get an instance of it, and call its methods. Don't write other methods in anonymous inner classes, it is invisible.
- The form is: new <class or interface> <body of the class>
- Implementation of anonymous classes