[英]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? 如果未在main方法中创建类的实例,是否会调用默认构造函数?
ex: 例如:
class A{
public static void main(String args[]){
System.out.print("Hello")
}
}
in this case, will the default constructor of A be called? 在这种情况下,是否会调用A的默认构造函数?
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.
Main方法是静态的,因此不需要创建A类的对象,因此不会调用构造函数。
Below is situation when default constructor is invoked because you create an instance of A class. 下面是因为您创建A类的实例而调用默认构造函数的情况。 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
的构造函数,如下面的语句中所示。
new A();
However, notice that main
method is static
. 但是,请注意
main
方法是static
。 static
area is also an object of the java.lang.Class
class. static
area也是java.lang.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, 查看完整的源代码,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.