Anonymous objects in Java

Source: Internet
Author: User
Tags thread class

An anonymous object is an object that does not explicitly give a name. Generally anonymous objects are used only once, and anonymous objects only open space in heap memory, and there is no reference to stack memory.

An ordinary constant string can represent an anonymous string object.

such as can

int len = "Hello". Length ();

As long as a class is abstract or an interface, the methods in its subclasses can be implemented using anonymous inner classes. The most common situation is in the implementation of multithreading, because to implement multithreading must inherit the thread class or inherit the Runnable interface

public class Anonymousdemo {public static void main (string[] args) {//TODO auto-generated method stubthread T  = new T Hread () {public void run () {for (int i = 1; i<=4; i++) {System.out.print (i+ "");}}; T.start ();}}

Output:1 2 3 4

public class Anonymousdemo {public static void main (string[] args) {//TODO auto-generated method Stubrunnable r = new Run  Nable () {@Overridepublic void Run () {//TODO auto-generated method stubfor (int i = 1; I <= 4; i++) {System.out.print (i+) ");}}}; Thread t = new Thread (r); T.start ();}}

Output:1 2 3 4

In addition to this, it is often used when adding listeners to a control.

Anonymous objects are basically passed as arguments to other class instantiation objects in real development, and the anonymous object is actually a heap memory space, and objects, whether anonymous or not, must be in the open heap memory space before they can be used.

Anonymous objects in Java

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.