简体   繁体   中英

What happens when you invoke new Object()?

I was trying to figure out what happens when you create an Object but I didn't find an Object() constructor method in Object.java, even if the documentation says that Object() exists.

Object does indeed have a no-arg constructor, You can see it by dumping the byte code for the class, using

javap -v java.lang.Object


public java.lang.Object();
Code:
Stack=0, Locals=1, Args_size=1
0:  return
LineNumberTable: 
line 20: 0
Object object = new Object();

That is perfectly valid code. It essentially does nothing. The only use I've seen with it is using it as a lock:

int c = 0;
Object lock = new Object();

...

synchronized(lock) { 
    c++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM