An overview: An object without a name, or an object that has no assigned value to any variable. An anonymous object is when an object is created, only the statement that created the object (the new object type), and there is no variable that receives the object.
For example:
Person class:
public class Person { public void eat(){ System.out.println("吃饭"); }}
Test class
public class Test { public static void main(String[] args){ //创建一个普通对象 Person person1 = new Person(); //创建一个匿名对象 new Person(); }}
Second, the characteristics and use of anonymous objects
1. Create anonymous object directly, no variable name
new Person().eat();//创建匿名对象,调用eat()方法
2. Anonymous objects can only be used once
new Person().eat();//创建匿名对象,调用eat()方法new Person().eat();//再次调用eat()方法,再次创建匿名对象
3. An anonymous object can be used as the method return value and the parameter that the method receives.
class Demo { public static Person getPerson(){ //普通方式 //Person p = new Person(); //return p; //匿名对象作为方法返回值 return new Person(); } public static void method(Person p){}}class Test { public static void main(String[] args) { //调用getPerson方法,得到一个Person对象 Person person = Demo.getPerson(); //调用method方法 Demo.method(person); //匿名对象作为方法接收的参数 Demo.method(new Person()); }}
In summary, an anonymous object is equivalent to a one-time object.
Anonymous objects in Java