当在main方法中未创建类的实例时,将调用默认构造函数吗?

时间:2018-10-11 18:00:00

标签: java

如果在main方法中未创建类的实例,则 默认的构造函数会被调用吗?

例如:

    text = Text()

    text.write("At the very beginning ")
    text.set_font("Arial")
    text.write("there was nothing.")

    assert text.show() == "[Arial]At the very beginning there was nothing.[Arial]"

在这种情况下,是否将调用A的默认构造函数?

2 个答案:

答案 0 :(得分:3)

在创建对象时会调用构造函数。主要方法是静态的,因此不需要创建A类的对象,因此不会调用构造函数。

以下是由于创建A类的实例而调用默认构造函数的情况。我创建自己的构造函数只是为了知道其中是否打印了文字,这就是调用它的证明

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");
   }
}

输出:

Constructor invoked
Text printed

答案 1 :(得分:0)

仅当您碰巧使用关键字A创建类的对象时,才会调用类new的构造函数,如下所示。

new A();

但是,请注意main方法是staticstatic区域也是java.lang.Class类的对象。因此,该类的构造函数将被调用。

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

查看完整的源代码,

相关问题