简体   繁体   中英

How object creation or constructors called implicitly in Java

I'm little confused about static methods and object creation in java.

As we know we can access static members in static method as here.

public static void main(String[] args){
// only static method from outside ( without any object )
}

But my stupid question is that why java allow this?

`public static void main(String[] args){
    Object o = new Object(); // is constructor implicitly static? 
                          // I'm sure no but why java allow this to call here?
    }

I know the above statement is similar to declare local variable in static method.

public static void main(String[] args){
 int a = 3;
}

But I'm little confused about constructor.

Constructors are not static. They are called on the instance, you just created. In byte code what happens.

  1. An new object is created, but it is not inilialised.
  2. The constructor is called on that object. In the constructor this is the object being initialised.

In bytecode, your main() method looks like this (result of the javap -c Main.class command):

  public static void main(java.lang.String[]);
    Code:
       0: new           #3                  // class java/lang/Object
       3: dup
       4: invokespecial #8                  // Method java/lang/Object."<init>":()V
       7: astore_1
       8: return

As you can see, at location 0, the new instruction is performed. Then, at location 4, the constructor is invoked on the newly created object.

This is also specified in the Java Virtual Machine Specification :

4.10.2.4. Instance Initialization Methods and Newly Created Objects

Creating a new class instance is a multistep process. The statement:

 ... new myClass(i, j, k); ... 

can be implemented by the following:

 ... new #1 // Allocate uninitialized space for myClass dup // Duplicate object on the operand stack iload_1 // Push i iload_2 // Push j iload_3 // Push k invokespecial #5 // Invoke myClass.<init> ... 

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