In the previous section we learned about inner classes, in this section we will learn about anonymous classes. So what is an anonymous class? As the name suggests, anonymous classes are classes that cannot have names. They cannot be referenced and can only be declared with the new statement when they are created.
To use anonymous inner classes we must inherit a parent class or implement an interface.
Things to note are:
1) Constructors cannot be defined in anonymous inner classes.
2) There cannot be any static member variables and static methods in anonymous inner classes.
3) Anonymous inner classes are local inner classes, so all restrictions on local inner classes also apply to anonymous inner classes.
The syntax format of anonymous classes is as follows:
classouterClass{//Define an anonymous class object1=newType(parameterList){//Anonymous class code};}
Note: Because anonymous classes are defined in the form of expressions, they end with a semicolon ;
For example:
classDotcpp{publicvoiddisplay(){System.out.println (inside the Dotcpp class);}}classAnonymousDemo{publicvoidcreateClass(){//The created anonymous class inherits the Dotcpp class Dotcppd1=newDotcpp(){publicvo iddisplay(){System.out.println(inside the anonymous class);}};d1.display();}}classMain{publicstaticvoidmain(String[]args){AnonymousDemoan=newAnonymousDemo();an.createClass();} }
The running results are as follows:
inside anonymous class
For example:
interfaceDotcpp{publicvoiddisplay();}classAnonymousDemo{publicvoidcreateClass(){//The created anonymous class implements the Dotcpp interface Dotcppd1=newDotcpp(){publicvoiddisplay(){Sy stem.out.println (inside the anonymous class);}};d1.display();}}classMain{publicstaticvoidmain(String[]args){AnonymousDemoan=newAnonymousDemo();an.createClass();}}
The running results are as follows:
inside anonymous class
Okay, everyone can experiment on the computer and digest and absorb the content of this section.