简体   繁体   中英

When an instance of a class is not created in the main method, will the default constructor be called?

When an instance of a class is not created in the main method, will the default constructor be called?

ex:

class A{
    public static void main(String args[]){
        System.out.print("Hello")
    }
}

in this case, will the default constructor of A be called?

Constructor is invoke when you create object. Main method is static so it is not needed to create object of A class so the constructor won't be invoked.

Below is situation when default constructor is invoked because you create an instance of A class. I create my own constructor just to know if the text inside of it is printed that's the proof that it is invoked

public class A {

   public static void main(String[] args) {
       A a = new A();
       a.print();
   }

   public A()
   {
       System.out.println("Constructor invoked");
   }

   private void print()
   {
       System.out.println("Text printed");
   }
}

Output:

Constructor invoked
Text printed

The constructor of your class A will only get called if you happen to create an object of your class using the keyword new , like in the statement below.

new A();

However, notice that main method is static . static area is also an object of the java.lang.Class class. So the constructor of the that class will be called.

/*
 * Constructor. Only the Java Virtual Machine creates Class
 * objects.
*/
private Class() {}

View the full source code,

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