[英]Can we say non static block as constructor of class?
class VI{
{
System.out.println("Non static block called");
}
VI()
{
System.out.println("Constructor block called");
}
public static void main(String a[])
{
VI v=new VI();
}
}
The code snippet comprises class again it comprised of non static block along with constructor. 该代码段再次包含类,它由非静态块以及构造函数组成。
So, when obejct of class is created the non static block will be called and after that constructor is called. 因此,当创建类的对象时,将调用非静态块,然后调用该构造函数。
So, can we say non static block as constructor of class? 那么,我们可以说非静态块作为类的构造函数吗?
vivek@ubuntu:~/Prime_project/python-SLR-parser$ javac VI.java
vivek@ubuntu:~/Prime_project/python-SLR-parser$ java VI
Non static block called
Constructor block called
vivek@ubuntu:~/Prime_project/python-SLR-parser$
No, an initializer block is not a constructor. 不,初始化程序块不是构造函数。
However, the code inside it is copied into every constructor according to the Java Tutorials : 但是,其中的代码会根据Java Tutorials复制到每个构造函数中:
The Java compiler copies initializer blocks into every constructor. Java编译器将初始化程序块复制到每个构造函数中。 Therefore, this approach can be used to share a block of code between multiple constructors. 因此,该方法可用于在多个构造函数之间共享代码块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.