Anonymous objects in Java

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.