Calling a Java method with no name

后端 未结 8 1416
迷失自我
迷失自我 2020-11-28 02:34

I\'m looking at the code below and found something a bit strange:

public class Sequence {
    Sequence() {
        System.out.print(\"c \");
    }

    {
            


        
8条回答
  •  隐瞒了意图╮
    2020-11-28 02:53

    Its not a method but a initialization block.

     {
        System.out.print("y ");
     }
    

    It will be executed before the constructor call. While

    static {
            System.out.print("x ");
           }
    

    is static initialization block which is executed when class is loaded by class loader.

    So when you run your code
    1. Class is loaded by class loader so static initialization block is executed
    Output: x is printed
    2. Object is created so initialization block is executed and then constuctor is called
    Output: y is printed followed by c
    3. Main method is invoked which in turn invokes go method
    Output: g is printed

    Final output: x y c g
    This might help http://blog.sanaulla.info/2008/06/30/initialization-blocks-in-java/

提交回复
热议问题