Anonymous objects, Java

Source: Internet
Author: User

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

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.