简体   繁体   English

我们可以说非静态块作为类的构造函数吗?

[英]Can we say non static block as constructor of class?

Code: 码:

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? 那么,我们可以说非静态块作为类的构造函数吗?

Terminal commands: 终端命令:

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.

相关问题 我们可以在Java的非静态类中具有静态块吗? - can we have static block in non static class in java? 从 static 块我们无法访问 super() 或 this() 但在 static 初始化块中我们如何访问构造函数? - From static block we can't access super() or this() but in static Initialization block how can we access a constructor? 我们可以在类静态块中调用ejb吗? - Can we call ejb in class static block? 在非静态块之前调用构造函数? - Constructor is called before non-static block? 我们可以直接导入非静态方法而不导入 class(就像我们对 static 方法所做的那样)? - Can we directly import non-static methods without importing class (like we do for static methods)? 我们可以调用类构造函数吗? - Can we invoke a class constructor? 带有私有构造函数的非静态类上的NoClassDefFoundError - NoClassDefFoundError on Non-static class with private constructor 为什么我们不能在(非静态)内部类(Java 16 之前)中使用静态方法? - Why can't we have static method in a (non-static) inner class (pre-Java 16)? 我们无法从静态方法访问非静态实例,但可以启动类。 怎么样? - We cant access non static instance from a static method, but can initiate a class. how? 将静态类引用传递给非静态类的构造函数 - Pass static class reference to a constructor of non-static class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM