code

이름없이 Java 메서드 호출

codestyles 2020. 8. 20. 18:47
반응형

이름없이 Java 메서드 호출


아래 코드를보고 약간 이상한 것을 발견했습니다.

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

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

    public static void main(String[] args) {
        new Sequence().go();
    }

    void go() {
        System.out.print("g ");
    }

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

System.outwith "y"가 메서드 선언에 속하지 않기 때문에 컴파일 오류가 발생할 것으로 예상 했습니다 { }. 이것이 유효한 이유는 무엇입니까? 이 코드가 어떻게 호출되어야하는지 모르겠습니다.

이것을 실행할 x y c g때도 생성됩니다 . 왜 static { }시퀀스 생성자보다 먼저 get이 호출됩니까?


이:

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

A는 정적 초기화 블록 , 그리고 클래스가로드 될 때 호출된다. 원하는만큼 클래스에 포함 할 수 있으며 모양 순서대로 (위에서 아래로) 실행됩니다.

이:

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

초기화 블록 이며 코드는 클래스의 각 생성자 시작 부분에 복사됩니다. 따라서 클래스의 생성자가 많고 모두 처음에 공통된 작업을 수행해야하는 경우 코드를 한 번만 작성하고 이와 같은 초기화 블록 에 넣으면됩니다 .

따라서 출력이 완벽하게 이해됩니다.

Stanley가 아래에 언급 했듯이 자세한 내용은 초기화 블록설명하는 Oracle 자습서의 섹션 을 참조하십시오.


메소드가 아니라 초기화 블록 입니다.

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

생성자 호출 전에 실행됩니다. 동안

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

정적 초기화 블록 클래스는 클래스 로더에 의해 로딩 될 때 실행된다.

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/


That's an instance initialization block followed by a static initialization block.

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

gets called when you create an instance of the class.

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

gets called when the class is loaded by the class loader. So when you do

new Sequence().go();

the class gets loaded, so it executes static {}, then it executes the instance initialization block {}, afterwards the body of the constructor is called, and then the method on the newly created instance. Ergo the output x y c g.


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

Is a static block and is called during Class Loading

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

Is an initialization block

You can have multiple initialization blocks in a class in which case they execute in the sequence in which they appear in the class.

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


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

is an initialization block shared by the class(as indicated by static), which is executed first.

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

}

is an initialization block shared by all objects(constructors) of the class, which comes next.

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

is a particular constructor for the class, which is executed third. The instance initialization block is invoked first every time the constructor is executed. That's why "y" comes just before "c".

void go() {
        System.out.print("g ");
}

is just an instance method associated with objects constructed using the constructor above, which comes last.


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

These kinds of blocks are called initializer block. It is executed every time you create an instance of a class. At compile time, this code is moved into every constructor of your class.

Where as in case of static initializer block: -

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

it is executed once when the class is loaded. We generally use static initializer block when the initialization of a static field, require multiple steps.


It is used as an initialisation block and runs after any static declaration. It could be used to ensure that no one else can create an instance of the class (In the same way you would use a private constructor) as with the Singleton design pattern.


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

Static blocks are only executed once when the class is loaded and initialized by the JRE.

And non-static block will be call every time your are creating a new instance and it will be call just before the Constructor.

As here you've created only 1 instance of Sequence so constructed has been called after non-static blocks and then the method which actually your goal.

참고URL : https://stackoverflow.com/questions/13699075/calling-a-java-method-with-no-name

반응형