Why Can You Instantiate a Class within its Definition?

前端 未结 9 1823
无人共我
无人共我 2020-12-24 13:22

A coworker (who is very new to Java) stopped in today and asked what seemed like a very simple question. Unfortunately, I did an absolutely horrible job of trying to explain

9条回答
  •  春和景丽
    2020-12-24 13:51

    If your coworker is coming from a C or pascal programming background this question is abolutely logical. In a C program methods have to be declared above the line where they are first used. As its not always practical to order functions in this order, there are forward declarations that just give the methods name, return type and parameters, without defining the function body:

    // forward declaration
    void doSomething(void);
    
    void doSomethingElse(void) {
        doSomething();
    }
    
    // function definition
    void doSomething(void) {
        ...
    }
    

    This was done to simplify the creation of a parser and to allow faster parsing since fewer passes over the source are needed. In Java however, identifiers are allowed to be used before their point of definition. Therefor parsing has to happen in several phases. After a syntax tree corresponding to the source code is build, this tree is traversed to determine all definitions of classes or methods. The method bodies are processed at a later stage, when all information about the names in scope are known.

    So by the point that the method body of your main method is processed the compiler knows of the default constructor of your class and its doIt method and can generate the correct bytecode to call exactly this method.

提交回复
热议问题