The concept of anonymous objects
an anonymous object is a statement that creates an object, but does not assign an object address value to a variable .
such as: A class that already exists:
public class person{
public void Eat () {
System.out.println ();
}
}
Create a Normal object
Person p = new person ();
Create an anonymous object
New Person ();
Characteristics of Anonymous objects
create anonymous objects directly using, without variable names .
The new person (). Eat ()//eat method is called by a person object that has no name.
An anonymous object can only be used once if its reference variable is not specified.
New person (). Eat (); Create an anonymous object, call the Eat method
New person (). Eat (); To re-create an anonymous object by calling the Eat method again
An anonymous object can be used as a parameter that is received by a method, a method return value
class Demo {
Public Static Person Getperson () {
Normal way
Person p = new person ();
return p;
Anonymous object as method return value
return New Person ();
}
Public Static void Method (person p) {}
}
class Test {
Public Static void Main (string[] args) {
Call the Getperson method to get a person object
Person person = Demo. Getperson ();
Call method Methods
Demo. Method (person);
An anonymous object is a parameter that is received as a method
Demo. Method (new person ());
}
}
Anonymous objects, Java