vivek narsale
vivek narsale

Reputation: 360

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$ 

Upvotes: 1

Views: 142

Answers (1)

Keppil
Keppil

Reputation: 46219

No, an initializer block is not a constructor.

However, the code inside it is copied into every constructor according to the Java Tutorials:

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

Upvotes: 4

Related Questions