Anonymous object: an object without a name.
Non-anonymous object:
ClassName c=new ClassName();
c.run();
Anonymous object:
new ClassName().run();
Notes:
1. When the object calls the method only once, it can be simplified into an anonymous object.
2. Two anonymous objects cannot be the same object.
3. Generally, attribute values are not assigned to anonymous objects, because they can never be obtained.
4. Once run, it will be recycled directly, saving memory space.
Example of code used by anonymous objects:
public class Anony{int a=1;int b=2;void run(){System.out.println(a+b);}public static void main(String[] args){new Anony().a=10; //Anonymous object cannot be reassigned, and the assignment still fails Anony a=new Anony();a.run(); //Create the object anonymously and call the method}}Running results:
3
3
Anonymous inner class: Anonymous inner class is an inner class without a name.
Format:
ClassName object=new ClassName(){
/*Code Block*/
};
Notes:
1. Anonymous internal classes must inherit a parent class or implement an interface.
Abstract class code example: (Same as interface)
abstract class AnonyTest{int a=1;int b=2; public abstract void run();}public class AnonyInner{public static void main(String[] args){AnonyTest a=new AnonyTest(){ //Abstract anonymous class public void run() {System.out.println(a+b);}};a.run();}}If you do not use anonymous inner classes to implement abstract methods:
abstract class AnonyTest{int a=1;int b=2; public abstract void run();}class AnonyDemo extends AnonyTest{public void run() {System.out.println(a+b);}}public class AnonyInner{public static void main(String[] args) {AnonyTest a=new AnonyDemo(); //Turn up the object a.run();}}Running results:
3