Java anonymous objects and anonymous internal classes, java anonymous objects
Anonymous object: an object without a name.
Non-Anonymous objects:
ClassName c = new ClassName ();
C. run ();
Anonymous object:
New ClassName (). run ();
Note:
1. When an object calls a method only once, it can be simplified to an anonymous object.
2. Two anonymous objects cannot be the same object.
3. Generally, attribute values are not assigned to anonymous objects because they cannot be obtained.
4. If you run it once, it will be recycled directly, saving memory space.
Example 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; // The anonymous object cannot be assigned a value again, and the value assignment still fails. Anony a = new Anony ();. run (); // call the new Anony () method by creating an object (). run (); // create an object anonymously and call the method }}
Running result:
3
3
Anonymous internal class: anonymous internal class is an internal class without a name.
Format:
ClassName object = new ClassName (){
/* Code block */
};
Note:
1. An anonymous internal class must inherit a parent class or implement an interface.
Example of the abstract class code: (the same 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) ;}};. run ();}}
If you do not use anonymous internal 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 (); // upload object. run ();}}
Running result:
3