开发者

Java constructor without name?

开发者 https://www.devze.com 2023-02-27 05:34 出处:网络
When I run the below code I am getting output as: static block TEst block main block How does the string \"TEst block\" gets printed? Is it considered as constructor?

When I run the below code I am getting output as:

static block
TEst block
main block

How does the string "TEst block" gets printed? Is it considered as constructor?

public class TestBlk {

s开发者_开发问答tatic {
    System.out.println("static block");
}

{
    System.out.println("TEst block");
}


public static void main(String args[]){
    TestBlk blk=new TestBlk();
    System.out.println("main block");

}
}


It's an instance initialiser, together with an default constructor.

A class without an explicit constructor, is given a synthetic, public, no-args constructor.

Constructors without a call to this() or super() (possibly with arguments) are given an implicit call to super() (without arguments, possibly something odd happens with inner classes).

Immediately after an implicit or explicit call to super(), all the code in field initialisers and instance initialisers gets inserted in the order it appears in the source code.

So after javac has finished with your code it looks a little like:

public class TestBlk {

    static {
        System.out.println("static block");
    }

    public TestBlk() {
        // Call constructor of java.lang.Object.
        super();

        // From instance (and field)initialiser.
        System.out.println("TEst block");

        // Rest of constructor:
    }


    public static void main(String args[]){
        TestBlk blk = new TestBlk();
        System.out.println("main block");
    }
}


What you have here is called: initialization block.

An initialization block is a block of code between braces that is executed before the object of the class is created.

There are two types of initialization blocks:

  1. Non static initialization block.

    { System.out.println("TEst block"); }

  2. Static initialization block.

    static { System.out.println("static block"); }

More specific, I like the explanation from here:

Note that any initialization block present in the class is executed before the constructor.

So now the question comes why we need constructors if we have initialization blocks. The answer is we don't need the default constructor but initialization block cannot be parameterized and so you cannot have objects taking values from out side and so initialization block is not a substitute for constructor.


It is called as a part of object construction when you call new TestBlk().


{
    System.out.println("TEst block");
}

That's an initialization block. See my answer to this other question.

0

精彩评论

暂无评论...
验证码 换一张
取 消