Why Can You Instantiate a Class within its Definition?

前端 未结 9 1824
无人共我
无人共我 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 14:00

    The same reason you can call a method on line 42 that isn't defined until line 78? Java isn't a scripting language, so things don't have to be declared before they are used (this is even true of some scripting languages, actually). Class definitions are considered as a whole at compile time.

    You can even instantiate an object of a class in its own constructor:

    public class Test {
        Test a;
    
        Test() {
            a = new Test();
        }
    
        public static void main(String[] args) {
            System.out.println(new Test());
        }
    }
    

    This produces... wait for it... a java.lang.StackOverflowError.

提交回复
热议问题